如何解决为什么简单表单在 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,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,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。