rails 中评分最高的评论

Highest rating comment in rails

我试图在产品展示页面中显示评分最高的评论,但它显示的是 # 而不是评论。有什么想法吗?

#comment model
class Comment < ApplicationRecord
 belongs_to :user
 belongs_to :product

 scope :rating_desc, -> { order(rating: :desc) }
 scope :rating_asc, -> { order(rating: :asc) }
end

#product model
class Product < ApplicationRecord
  has_many :orders
  has_many :comments

  def highest_rating_comment
    comments.rating_desc.first
  end
end

#product show page
<%= @product.highest_rating_comment %>

如果您的输出类似于 "#<Comment:0x007fb9ea9561d0>",那么您看到的是在 @product.highest_rating_comment 上调用 to_s 的结果。基本上,您看到的是对象在内存中的位置的文本表示。

您可能想要的是评论的内容。由于您没有提供您的架构,我无法说出该字段的名称 - 也许是 @product.highest_rating_comment.comment

显示inspect方法的结果。您需要输出评级字段的值。添加对产品展示页面的更改:

#product show page
<%= @product.highest_rating_comment.try(:rating) %>