I am using Ruby on Rails 3.0.7 and, for performance reason, I would like to avoid loading associated objects on retrieving a class obect. That is, if I have an Article class\model with a has_many :users statement I would like to not load associated User objects when I retrieve an Article object (I think this behavior depends on the Ruby on Rails “Convention over Configuration” principle).
How can I do that?
As noted by Yet Another Geek, Rails (ActiveRecord) doesn’t load the relationship objects by default. Rather, it goes and gets them when you ask for them. If you don’t need the objects of that relationship, it will never bother to load them, saving database time.
If you do need then, it will go retrieve them lazily (by default). If you know you’ll need all (or many) of the objects of the relationship (assuming x-to-many), then you can use the
:includemodifier to yourfindto get them all up front (which will be a lot faster since it can do that with a single db call). Knowing and taking advantage of the ability to eagerly load relationship objects is an important thing.All that being said, the behavior you want (not loading the objects if you don’t need them) is the default behavior and you should be all set. The rest of the answer was just some context that may be useful to you later.