views:

204

answers:

3

hi, I have two models, user and group. I also have a joining table groups_users. I have an association in the group model:

has_many :groups_users
has_many :users, :through=> :groups_users

I would like to add pending_users which would be the same as the users association but contain some conditions. I wish to set it up as an association so that all the conditions are handled in the sql call. I know there's a way to have multiple accessors for the same model, even if the name is not related to what the table names actually are. Is it class_name?

Any help would be appreciated, thanks

+1  A: 

This should be pretty close - more on has_many.

has_many :pending_users, 
         :through => :groups_users, 
         :source => :users, 
         :conditions => {:pending => true}

:pending is probably called something else - however you determine your pending users. As a side note - usually when you see a user/group model the association is called membership.

Andy Gaskell
+1  A: 

Use named_scopes, they're your friend

Have you tried using a named_scope on the Group model?

Because everything is actually a proxy until you actually need the data, you'll end up with a single query anyway if you do this:

class User < ActiveRecord::Base
  named_scope :pending, :conditions => { :status => 'pending' }

and then:

a_group.users.pending

Confirmation

I ran the following code with an existing app of mine:

Feature.find(6).comments.published

It results in this query (ignoring the first query to get feature 6):

SELECT    * 
FROM      `comments` 
WHERE     (`comments`.feature_id = 6) 
  AND     ((`comments`.`status` = 'published') AND (`comments`.feature_id = 6))
ORDER BY  created_at

And here's the relevant model code:

class Feature < ActiveRecord::Base
  has_many    :comments

class Comment < ActiveRecord::Base
  belongs_to  :feature
  named_scope :published, :conditions => { :status => 'published' }
kch
Declare the pending in the User model, not the Groupclass User < ActiveRecord::Base named_scope :pending...end
ez
Oops. Indeed. Fixed.
kch
A: 

In the User model:

named_scope :pending, :include => :groups_users, :conditions => ["group_users.pending = ?", true]

That's if you have a bool column named "pending" in the join table group_users.

Edit: Btw, with this you can do stuff like:

Group.find(id).users.pending(:conditions => ["insert_sql_where_clause", arguments])
Lonecat