I have the following User model on my application (simplified)
class User < ActiveRecord::Base
attr_accessible :username, :email, :password, :company_id, :role_id belongs_to :company belongs_to :roleend
My question is: Is my user carrying around all the Company model attributes during all the time of his session or only when a user.company is executed?
I believe the company method exists as a Relation during the session, but I’m not sure.
If my user is indeed carrying his Company object around, is there a way to prevent this from happening and making que database query only when it is actually called?
Thanks in advance.
Lazy loading(which is by default) means the association methods will be called only when they are required.
So your user object has
company_idbut notcompanyobject. Whenever it found user.company it will then executes the DB Query.However you can
eager loadit withincludesmethod.Eager loading is generally helpful when you are loading multiple
users, and inviewyou will be calling user.company by iterating overusers, which will run DB query for each call of user.company(i.e. hitting a db query to same table each time). To avoid this eager loading is helpful, so that it loads all company data for allusersit fetched..