Rails模型范围可以获取字段排序的前3个记录

时间:2016-02-24 00:43:22

标签: ruby-on-rails ruby postgresql activerecord

我有一个简单的模型关联:

Product has_many Review

我在视图中迭代了产品的评论,但是,我只想抓住产品的前3条评论,按照它的score整数字段排序。

我想做点什么:

@product = Product.find(1).includes(:testimonials, :stores, :top_three_reasons)

然后迭代:

@product.reviews.each do |x|
  puts x.title
end 

我怎样才能做到这一点?目前,对于每种产品,我们都包含每一次评论,而且速度非常慢。我们只想包含前三个评论,以避免重复查询。

2 个答案:

答案 0 :(得分:0)

我建议为top_reviews创建专用范围。

class Product << AR::Base
  has_many :top_reviews, -> {order(score: :desc).limit(3)}
end

...

@product = Product.find(1)
@product.top_reviews.each do |x|
  puts x.title
end

答案 1 :(得分:0)

这样怎么样,

@product.reviews.order("score DESC").limit(3).each do |x|
  puts x.title
end