views:

117

answers:

1

Two models (Rails 2.3.8):

User; username & disabled properties; User has_one :profile Profile; full_name & hidden properties

I am trying to create a named_scope that eliminate the disabled=1 and hidden=1 User-Profiles. Moreover, while the User model is usually used in conjunction with the Profile model, I would like the flexibility to be able specify this using the :include => :profile syntax.

I have the following User named_scope:

  named_scope :visible, {
    :joins => "INNER JOIN profiles ON users.id=profiles.user_id",
    :conditions => ["users.disabled = ? AND profiles.hidden = ?", false, false]
  }

This works as expected when just reference the User model:

>> User.visible.map(&:username).flatten
=> ["user a", "user b", "user c", "user d"]

However, when I attempt to include the Profile model:

User.visible(:include=> :profiles).profile.map(&:full_name).flatten

I get an error that reads:

NoMethodError: undefined method `profile' for #<User:0x1030bc828>

Am I able to cross model-collection boundaries in this manner?

A: 

To access a user's profile, you have to use something like

@user = User.visible(:include => :profiles)
@user.first.profile

Or, if what you want is all full_names, I believe you should do something like

# untested
User.visible(:include=> :profiles).map(&:profile).collect{ |p| p.full_name }

But probably there's a better way... It doesn't look pretty =P

j.