2017-02-28 104 views
1

我試圖在產品展示頁面中以最高評分顯示評論,但它顯示#而不是評論。任何想法爲什麼?在導軌中評分最高評論

#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 %> 

回答

0

它顯示了inspect方法的結果。您需要輸出評分字段的值。添加更改產品展示頁:

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

如果你的輸出看起來像"#<Comment:0x007fb9ea9561d0>",那麼你看到的是呼籲@product.highest_rating_commentto_s的結果。基本上你可以看到對象在內存中的位置的文本表示。

你可能想要的是評論的內容。既然你沒有提供你的模式,我不能說這個字段叫什麼 - 也許@product.highest_rating_comment.comment

+0

你說得對,我試過@ product.highest_rating_comment.body,我看到評論的身體。萬分感謝! – BoB

+0

太棒了,很高興幫助!你介意接受我的回答嗎?謝謝! – Brian

+0

這個解決方案可以在本地工作,但在Heroku上會出錯。我試過這個其他的解決方案,它在本地和Heroku都能正常工作: <%= @ product.highest_rating_comment.try(:rating)%> 感謝您的幫助! – BoB