在导轨中评分最高评论
问题描述:
我试图在产品展示页面中以最高评分显示评论,但它显示#而不是评论。任何想法为什么?在导轨中评分最高评论
#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 %>
答
它显示了inspect
方法的结果。您需要输出评分字段的值。添加更改产品展示页:
#product show page
<%= @product.highest_rating_comment.try(:rating) %>
答
如果你的输出看起来像"#<Comment:0x007fb9ea9561d0>"
,那么你看到的是呼吁@product.highest_rating_comment
to_s
的结果。基本上你可以看到对象在内存中的位置的文本表示。
你可能想要的是评论的内容。既然你没有提供你的模式,我不能说这个字段叫什么 - 也许@product.highest_rating_comment.comment
?
你说得对,我试过@ product.highest_rating_comment.body,我看到评论的身体。万分感谢! – BoB
太棒了,很高兴帮助!你介意接受我的回答吗?谢谢! – Brian
这个解决方案可以在本地工作,但在Heroku上会出错。我试过这个其他的解决方案,它在本地和Heroku都能正常工作: 感谢您的帮助! – BoB