【问题标题】:Highest rating comment in railsrails中评分最高的评论
【发布时间】:2017-02-28 20:17:43
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby rails-models


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-15
        • 2014-01-18
        • 2012-01-17
        • 2011-04-15
        • 2012-03-18
        • 2023-04-10
        • 1970-01-01
        • 2019-10-01
        相关资源
        最近更新 更多