views:

107

answers:

1

First let me show some code.

class User
  has_and_belongs_to_many :roles
  named_scope :employees, { :conditions => ["roles.name = 'Employee'"], :include => :roles }
end

OK, so later in a controller I wanted to search for all the employees right. I set the named scope up to help do that with the join and conditional search. But the problem is in the view I want to show all of that users roles, but It will only display the employee role.

Is there anyway that I can say "user.roles" and have the be lazy loaded in the view after I have already eager loaded it?

+2  A: 

The documentation for habtm (as well as has_many) states that you can access the collection with an optional parameter:

collection(force_reload = false)

Returns an array of all the associated objects. An empty array is returned if none are found.

You can reload the roles with user.roles(true).

Ian Terrell
You sir are fantastic. I never knew that existed. Guess I should have read the documentation a little more thoroughly.Thanks for the good answer!
taelor