0

我的一个模型中有这个 named_scope:

named_scope :latest_100,
            :from => '(select * from videos order by videos.created_at desc limit 0, 100) as videos'

它的目的是创建一个包含最后 100 个视频的池(将该结果作为“视频”返回,以便其他范围在该数据集上运行),然后我可以在此之后链接范围并从该结果池中过滤记录。

# video.rb
named_scope :most_popular, :order => 'popularity'
named_scope :take_5, :limit => 5

# video_controller.rb
# it gets the latest 100 videos, then sorts those by popularity, and takes the top 5.
@videos = Video.latest_100.most_popular.take_5

是否有与 Arel 相同的声明?

4

1 回答 1

0

Arel 中有一个 .from() 方法。

我以以下方式使用它:

# video.rb
scope :latest_100, from('(select * from videos limit 100 order by created_at desc) as videos')
scope :most_popular, order('popularity')
scope :take_5, limit(5)

# video_controller.rb
@videos = Video.latest_100.most_popular.take_5

latest_100 将创建一个有效视频池,您可以从中提取前 5 个最受欢迎的视频。

于 2011-09-30T19:52:20.560 回答