Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails模型的作用域可获取按字段排序的前3条记录_Ruby On Rails_Ruby_Postgresql_Activerecord - Fatal编程技术网

Ruby on rails Rails模型的作用域可获取按字段排序的前3条记录

Ruby on rails Rails模型的作用域可获取按字段排序的前3条记录,ruby-on-rails,ruby,postgresql,activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,我有一个简单的模型关联: Product has_many Review 在我看来,我反复浏览了一个产品的评论,但是,我只想获取一个产品的前3个评论,按它的scoreinteger字段排序 我想做一些类似的事情: @product = Product.find(1).includes(:testimonials, :stores, :top_three_reasons) 然后迭代: @product.reviews.each do |x| puts x.title end 我怎样才

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

Product has_many Review
在我看来,我反复浏览了一个产品的评论,但是,我只想获取一个产品的前3个评论,按它的
score
integer字段排序

我想做一些类似的事情:

@product = Product.find(1).includes(:testimonials, :stores, :top_three_reasons)
然后迭代:

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


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

我建议为
前三名评论创建一个专用范围

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
类产品{顺序(分数::desc).limit(3)}
结束
...
@产品=产品。查找(1)
@product.top|u reviews.each do|x|
放置x.title
结束
像这样怎么样

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

是的,但这意味着对于每一个
@产品
,我都会点击数据库进行每一次顶级评论,对吗?我试图完全避免这种情况。是的,对于每一种产品,你都会进行查询以找到前三名的评论。您最多只能进行两次查询。我不知道AR是否可以在
包含的
中使用修改后的关联来轻松拉动前三名:/