私のモデルには、次のフィールドがあります。
class Comment
include Mongoid::Document
field :author, type: String
field :author_email, type: String
field :author_url, type: String
field :author_ip, type: String
field :content, type: String
validates :author, presence: true, length: { minimum: 4 }
validates :content, presence: true, length: { minimum: 8 }
end
また、「コメンター」が提供できるフィールドを提出するためのフォームもあります。
<%= form_for [@article, @article.comments.build] do |f| %>
<div class='comment_content'>
<%= f.text_area :content %>
</div>
<div class='comment_author_email'>
<%= f.email_field :author_email %>
</div>
<div class='comment_author'>
<%= f.text_field :author %>
</div>
<div class='comment_author_url'>
<%= f.url_field :author_url %>
</div>
<div class='comment_submit'>
<%= f.submit %>
</div>
<% end %>
フィールド「著者」と「コンテンツ」が必要であり、他のフィールドは自動的に満たされています(ただし、動作しています)。問題は、ユーザーがオプションである「URL」フィールドを入力しない場合、モデルがコメントを保存しないことです。私のコントローラーに従ってください:
class CommentsController < ApplicationController
def create
@article = Article.find params[:article_id]
@comment = @article.comments.create(comment_params)
@comment.author_ip = request.remote_ip
if @comment.save
flash[:notice] = 'Comment published'
else
flash[:alert] = 'Comment not published'
end
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:content, :author_email, :author, :author_url)
end
end
コメントは保存できませんが、「アラート」は設定されておらず、「通知」も設定されていません。それはただクラッシュして方法全体をスキップするようです。すべてのフィールドが埋められている場合にのみコメントを保存できます。そうしないと、メッセージなしで失敗します。
何が足りないの?