在我的模型中,我有以下字段:

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

该评论无法保存,但没有设置“警报”,也没有“通知”。似乎它只是崩溃并跳过了整个方法。我只有在填写每个字段的情况下才能保存评论,否则它将失败而没有任何消息。

我想念什么?

有帮助吗?

解决方案

The first thing that comes to mind is that you are saving the comment twice for some reason. First you save it when using @article.comments.create(comment_params) instead on @article.comments.new(comment_params). So the first save fails with no flash.

I'd also recomend you applying some tests to see what's not working or at least using the debugger gem to sneek inside the code in action.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top