Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Working with named_scopes
4 Posts
Working with named_scopes

I've using named_scope and wanting to share my scopes with other models and queries. How can I use named_scope with other conditions from named_scope for joined model?

class Account < ActiveRecord::Base

named_scope :active, {:conditions => my_custom_sql_here}


class Person < ActiveRecord::Base

has_many :accounts


I wanna get just people with active accounts using my named scope like:

Person.all(:include => :accounts, :conditions => { :accounts => { use_my_named_scope active here...}})

there's any way to do it?

You could do something like this:

Account.active.find(:all, :include => :person).collect(&:person)

Of course, if you generally need access to the Person model associated with active accounts you could move the :include clause into the named_scope. Although, in that case you might want to consider moving the named_scope onto the Person model.

Hi Jonatas,

you can use the named scope directly on the association itself such as:

Person.accounts.active.all or Person.accounts.active.find(:all, :conditions => "other conditions") etc...

This should work just fine (assuming the named scope imposes conditions on columns in the accounts table) you can also chain scopes together if needed:


Cheers, Jeremy

There's any way to get the string with this scoped conditions? Because I need to get the string with sql. like:

sql = Account.named_scope(:active).conditions.to_sql # returns sql that do this scope

Person.all(:include => :accounts, :conditions => sql)

because I have a lot of other named_scopes to put and when I use:


It's doesn't work, but could get active accounts and not all people with active accounts.

I want to get all people with active accounts using my named_scope conditions.

I hope that you understand my question =)

Sorry for my poor english!

4 Posts
Login to add your message