Forum: Ruby on Rails Composing several named_scopes into another

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9347d4d9f9c4272f6a3297ea3a5976ac?d=identicon&s=25 Kip Cole (kipcole9)
on 2008-10-25 11:01
(Received via mailing list)
I have several named scopes in my app.  Some patterns are
used commonly.  For example:

Article.published_in(publication).published.viewable_by(current_user).included_in_index

Since this pattern is repeated, I'd like to be able to have a
named_scope that embeds this pattern.
I've tried defining a named_scope in terms of several changed
named_scopes but that doesn't work.

Is there a way to do this?  Something like:

named_scope :permitted, :lambda {|user, publication|
published_in(publication).published.viewable_by(user).included_in_index
}

I supposed a class method would be the natural alternative, but am
curious if there is indeed a way
to compose named_scopes.

Cheers, --Kip
5acba71393125496e93b9e434d8b63c9?d=identicon&s=25 Sjoerd Andringa (s-andringa)
on 2008-10-25 18:41
Kip Cole wrote:
> I have several named scopes in my app.  Some patterns are
> used commonly.  For example:
>
> Article.published_in(publication).published.viewable_by(current_user).included_in_index
>
> Since this pattern is repeated, I'd like to be able to have a
> named_scope that embeds this pattern.
> I've tried defining a named_scope in terms of several changed
> named_scopes but that doesn't work.
>
> Is there a way to do this?  Something like:
>
> named_scope :permitted, :lambda {|user, publication|
> published_in(publication).published.viewable_by(user).included_in_index
> }
>
> I supposed a class method would be the natural alternative, but am
> curious if there is indeed a way
> to compose named_scopes.
>
> Cheers, --Kip

It's not possible out of the box, but check out the patches posted in
this discussion:
http://rails.lighthouseapp.com/projects/8994/ticke...

It gives you a :through option for named_scope. So you can do:

named_scope :all, :conditions => ['deleted = ?', false]
named_scope :active, :conditions => ['active = ?', true], :through =>
:all
This topic is locked and can not be replied to.