您好我正在开发一个演示电子商务应用,我在其中创建了产品,用户和评论。 每个产品页面都应显示特定产品的注释。 我可以评论产品A,然后我可以看到产品A的所有评论,但是,如果我查看产品B的页面,我也会看到产品A的评论。所以基本上,所有评论都混淆了一长串而不是为产品排序...... 这是我的github:https://github.com/Adsidera/FreshObst 以下是评论的部分产品/ _comment.html.erb
<div class="product-reviews">
<% @comments.each do |comment| %>
<div class="row" style="padding-left:4%;">
<HR>
<p><small><%= comment.user.first_name %><em><%= " #{time_ago_in_words(comment.created_at)} ago" %></em></small></p>
<div class="rated" data-score="<%= comment.rating %>"></div>
<p><%= comment.body %></p>
<% if signed_in? && current_user.admin? %>
<p><%= link_to product_comment_path( @product, comment), method: :delete, data: { confirm: 'Are you sure?'} do %>
<i class="fa fa-trash-o fa-fw"></i>
<% end %>
</p>
<% end %>
</div>
<% end %>
这是评论控制器
class CommentsController < ApplicationController
# So admin abilities are applied to only these.
# So public can view product without signing in.
load_and_authorize_resource :only => [:destroy]
def index
end
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, alert: 'Review was created successfully'}
format.json {render :show, status: :created, location: @product}
else
format.html { redirect_to @product, alert: 'Review could not be saved'}
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def destroy
@product = Product.find(params[:product_id])
@comment = Comment.find(params[:id])
product = @comment.product
@comment.destroy
respond_to do |format|
format.html {redirect_to @product, alert: 'Comment deleted successfully'}
format.json {render :show, location: @product}
end
end
def show
end
private
def comment_params
params.require(:comment).permit(:user_id, :body, :rating)
end
end
这是我的产品控制器https://github.com/Adsidera/FreshObst/blob/master/app/controllers/products_controller.rb
的链接提前感谢您的帮助! 安娜
答案 0 :(得分:0)
问题在于产品控制器的show
方法,就像这样:
def show
@product = Product.find(params[:id])
# @comment = current_user.comment.build(comment_params)
@comments = @product.comments.order("created_at DESC")
@comments = Comment.paginate(:page => params[:page], :per_page => 3).order("created_at DESC")
end
应该是这样的:
def show
@product = Product.find(params[:id])
@comments = @product.comments.paginate(:page => params[:page], :per_page => 3).order("created_at DESC")
end