什么是活动关系(等)相当于:from

时间:2011-09-28 18:13:00

标签: ruby-on-rails ruby-on-rails-3 activerecord rails-3-upgrade active-relation

我的一个模型中有这个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相同的声明?

1 个答案:

答案 0 :(得分: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个。