【问题标题】:What's the ActiveRelation (arel) equivalent to :from什么是 ActiveRelation (arel) 相当于 :from
【发布时间】:2011-09-28 18:12:59
【问题描述】:

我的一个模型中有这个 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 有没有等价的说法?

【问题讨论】:

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


    【解决方案1】:

    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 个最受欢迎的视频。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多