3

In my model I have the following fields:

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

And I also have a form for submitting the fields the "commenter" may provide:

<%= 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 %>

The fields "author" and "content" are required, the others are automatically filled (but are working). The problem is, when a user does not fill the "URL" field, which is optional, the model does not save the comment. Following my 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

The comment fails to save, but no "alert" is set, neither "notice". It seems like it just crashes and skips the whole method. I can only save the comment if every field is filled, otherwise it will fail without any message.

What am I missing?

4

1 回答 1

1

首先想到的是您出于某种原因保存了两次评论。首先,在使用时保存@article.comments.create(comment_params)@article.comments.new(comment_params)。所以第一次保存失败,没有闪光灯。

我还建议您应用一些测试来查看什么不起作用,或者至少使用debugger gem来偷看正在运行的代码。

于 2013-11-07T05:33:08.850 回答