所以我收到以下错误:< p>
undefined method `errors' for #<Comment::ActiveRecord_Associations_CollectionProxy:0x00007f1a3e2ecf48>
我可以得到评论数之类的信息,但是,我无法显示任何验证错误。
这就是我所拥有的代码
_new_comment
<% if signed_in? %>
<div class="row">
<%= form_with(model: [@product, @product.comments.build], local: true) do |f| %>
<% if @product.comments.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.comments.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% @product.comments.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
comments_controller
class CommentsController < ApplicationController
def create
@product = Product.find(params[:product_id])
@comment = @product.comments.new(comment_params)
@comment.user = current_user
@comment.save
respond_to do |format|
if @comment.save
format.html { redirect_to @product, notice: 'Review was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { redirect_to @product, alert: 'Review was not saved successfully.' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def destroy
end
private
def comment_params
params.require(:comment).permit(:user_id, :body, :rating)
end
end
感谢您的帮助。
答案 0 :(得分:-1)
errors
对象上访问ActiveRecord::Relation
,但只能访问单个Comment
对象。create
中,您对未保存注释执行redirect_to(@product)
,注释将忽略已构建的@comment
对象并构建一个新对象(通过form_with(model: [@product, @product.comments.build])
)呈现评论表单时。相反,您只需要render
个具有已构建的@comment
对象的产品页面即可。@comment.save
动作中有两次create
。products_controller.rb
def show
# your current logic
@comment = @product.comments.build
# render
end
comments_controller.rb
class CommentsController < ApplicationController
def create
@product = Product.find(params[:product_id])
@comment = @product.comments.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @product, notice: 'Review was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render 'products/show', alert: 'Review was not saved successfully.' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
private
def comment_params
params.require(:comment).permit(:user_id, :body, :rating)
end
end
_new_comment.html.erb
<%= form_with(model: [@product, @comment], local: true) do |f| %>
<% if @comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% @comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<% end %>