I’ve got three nested models: user has many plates and plate has many fruits. I also have a current_user helper method that runs in the before filter to provide authentication. So when I get to my controller, I already have my user object. How can I load all the user’s plates and fruits at once?
In other words, I’d like to do something like:
@plates = current_user.plates(include: :fruits)
How can I achieve this?
I’m using Rails 3.1.3.
You will probably want to use the provided
#includesmethod on your relation. DO NOT USE#allunless you intend to immediately work through the records, it will immediately defeat many forms of caching.Perhaps something like:
@plates = current_user.plates.includes(:fruits)Unfortunately, there are portions of the Rails API that are not as well documented as they should be. I would recommend checking out the following resources if you have any further questions about the Rails query interface:
The query interface is possibly the most difficult part of the Rails stack to keep up with, especially with the changes made with Rails 3.0 and 3.1.