Search code examples
ruby-on-railsruby-on-rails-3activerecordrails-3-upgradeactive-relation

What's the ActiveRelation (arel) equivalent to :from


I have this named_scope in one of my models:

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

Its purpose is to create a pool of the last 100 videos (returning that results as 'videos' so the other scopes operate on that dataset), and then I can chain scopes after that and filter records out of that pool of results.

# 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

Is there an equivalent statement for Arel?


Solution

  • There exists a .from() method in Arel.

    I used it in the following manner:

    # 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
    

    The latest_100 will create a pool of valid videos from which you can pull the top 5 most popular.