Let's say that i have a User object in @user, already loaded. I want
to constantly refer to @user.role on a particular page (where User
belongs_to :role), so i want to 'eager load' the role association.
For the sake of argument, let's say i wasn't able to do this in the
normal way (ie with the :include option to a find call) when i loaded
the user out of the database in the first place, but need to do it
subsequent to that. Is that possible?
Let's say that i have a User object in @user, already loaded. I want
to constantly refer to @user.role on a particular page (where User
belongs_to :role), so i want to 'eager load' the role association.
For the sake of argument, let's say i wasn't able to do this in the
normal way (ie with the :include option to a find call) when i loaded
the user out of the database in the first place, but need to do it
subsequent to that. Is that possible?
Just to answer my own question, sort of, i think that i can do
@user[:role] = @user.role
and that sets the instance variable which is used for subsequent calls
to @user.role, effectively eager loading that association. is that
correct? Is this the same thing as the eager loading would do? eg, is
it precisely as prone to weird side effects as the regular eager
loading?
Max Williams wrote:
> Let's say that i have a User object in @user, already loaded. I want
> to constantly refer to @user.role on a particular page (where User
> belongs_to :role), so i want to 'eager load' the role association.
> For the sake of argument, let's say i wasn't able to do this in the
> normal way (ie with the :include option to a find call) when i loaded
> the user out of the database in the first place, but need to do it
> subsequent to that. Is that possible?
Just to answer my own question, sort of, i think that i can do
@user[:role] = @user.role
and that sets the instance variable which is used for subsequent calls
to @user.role, effectively eager loading that association. is that
correct? Is this the same thing as the eager loading would do? eg, is
it precisely as prone to weird side effects as the regular eager
loading?
It's not at all what normal eager loading would do.
if you do
class User < ActiveRecord::Base
class << self
public :preload_associations
end
end
Memoize the role if necessary (although I thought AR would do that for
you after the first load - not got time to check it out to be sure at
the moment)
In this case, i have a page which loads a partial twenty times. Each
partial calls a method on the user object (current_user as it happens)
which inspects its associated role object. So, if i don't eager load,
then the role gets loaded twenty times. I might be misunderstanding
your point though.
If it's the same user object throughout active record will cache the
loaded role object for you - no need for eager loading here.