Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

[patch] Named scope can accept other named scopes as an argument

#5201

Hey all,

I've created a patch for Rails 2-3-stable that will allow named_scopes to use other defined named_scopes as arguments. This allows chaining named scopes within another named_scope.

For example:

class Post < ActiveRecord::Base
  named_scope :title_starts_with, lambda {|letter| {:conditions => ["title LIKE ?", letter + "%"]}}
  named_scope :title_starts_with_w, title_starts_with("W")
  named_scope :title_starts_with_w_limit_one, title_starts_with("W").limit(1)
end

What is this good for? It replicates the new arel-based query_interface, and could allow users using rails 2.3.9 (if included) to begin migrating their ActiveRecord queries early on, before Rails 3 is released into the wild.

An example of the power of this change -- I created a small gem called fake_arel that takes advantage of calling named scopes within other named scopes:
http://github.com/gammons/fake_arel

This gem implements all of the new rails 3 query interface finders using named scopes.

  Reply.where(:id => 1)
  Reply.select("content,id").where("id > 1").order("id desc").limit(1)
  Topic.joins(:replies).limit(1)

Attached is a patch for 2-3-stable. I look forward to your opinions.

Reported by Grant Ammons · July 26th, 2010 @ 10:16 PM

State: wontfix
Milestone: 2.x
Assigned to: Santiago Pastorino Santiago Pastorino
Importance: Low

Activity

  1. Andrea Campi
    Andrea Campi
    • Tag changed from patch named_scope named_scopes arel 2-3-stable 2.3.9 to 2-3-stable, named_scope, patch

    October 16th, 2010 @ 11:49 PM

  2. Aditya Sanghi
    Aditya Sanghi
    • State changed from new to wontfix
    • Milestone set to 2.x
    • Assigned user set to Santiago Pastorino
    • Importance changed from to Low

    Grant, I doubt more features would be added to the 2.3x branch. Could your patch be integrated into your fake_are gem itself? Something like the rails_upgrade plugin.

    Marking the ticket wont fix but assigning to Santiago for his views. He might reopen if he feels otherwise.

    October 17th, 2010 @ 05:55 AM

  3. Grant Ammons
    Grant Ammons

    This ticket can be closed. Because Rails 3 is out, I agree that this functionality does not need to be in ActiveRecord. If people would like to use an arel syntax in rails 2 applications, they should use fake_arel.

    October 17th, 2010 @ 03:20 PM