In meinem Modell habe ich die folgenden Felder:
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
Und ich habe auch ein Formular für die Übermittlung der Felder, die der "Kommentator" möglicherweise liefern:
<%= 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 %>
Die Felder "Autor" und "Inhalt" sind erforderlich, die anderen werden automatisch gefüllt (aber funktionieren). Das Problem ist, wenn ein Benutzer das Feld "URL" nicht füllt, was optional ist, speichert das Modell den Kommentar nicht. Folgt meinem Controller:
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
Der Kommentar kann nicht speichern, aber kein "Alarm" wird festgelegt, weder "Hinweis". Es scheint, als würde es nur abgestürzt und die gesamte Methode übersprungen. Ich kann den Kommentar nur speichern, wenn jedes Feld gefüllt ist, sonst fehlschlägt er ohne Nachricht.
Was vermisse ich?