为什么简单表单在 Rails 中不显示验证错误消息?

Why does simple form not show validation error messages in Rails?

如果验证不匹配时重定向时的 :new 视图以及我希望在何处查看错误消息:

<%= simple_form_for ([ @recipe, @recipe.comments.build]), class:"comment-form" do |f| %>
<%= f.error_notification %>
<%= f.object.errors.full_messages.join(", ") if f.object.errors.any? %>
<%= f.input :name, label: false, placeholder: "Your name", input_html: { value: @comment.name } %>
<%= f.input :comment, label: false, placeholder: "Tell us about your experience", input_html: { value: @comment.comment } %>
<%= f.submit "Submit", class: "btn-comment-submit" %>
<% end %>

这是我的控制器:

  def new
    @recipe = Recipe.find(params[:recipe_id])
    @comment = Comment.new
    @comment = @recipe.comments.build
  end

  def create
    @comment = Comment.new(comment_params)
    @recipe = Recipe.find(params[:recipe_id])
    @comment.recipe = @recipe
    if @comment.save
      redirect_to recipe_path(@recipe)
    else
      render :new
    end
  end

您没有将您在控制器中创建的 @comment 实例绑定到表单。相反 @recipe.comments.build 总是创建 Comment 的新实例。

您可以使用条件设置模型:

<%= simple_form_for([@recipe, @comment || @recipe.comments.build]) do |form| %> 
  <%= f.error_notification %>
  <%= f.object.errors.full_messages.join(", ") if f.object.errors.any? %>
  <%= f.input :name, label: false, placeholder: "Your name" %>
  <%= f.input :comment, label: false, placeholder: "Tell us about your experience" %>
  <%= f.submit "Submit", class: "btn-comment-submit" %>
<% end %>

请注意,您不需要为输入设置值。表单生成器将为您完成。这就是它的全部意义。

或者您最好确保在控制器中设置 @comment 以使视图尽可能简单:

class RecipiesController < ApplicationController
  before_action :set_recipe
  # ...
  def show
    @comment = @recipe.comments.new
  end

  # ...
end
<%= simple_form_for([@recipe, @comment]) do |form| %>
   # ...
<% end %>

您可以清理您的创建操作,只创建食谱的评论:

def create
  @recipe = Recipe.find(params[:recipe_id])
  @comment = @recipe.comments.new(comment_params)
  if @comment.save
    redirect_to @recipe
  else
    render :new
  end
end