Get all associated data for all records of a model type in Rails? -
how meld getting of associated data of records of given model?
i have following models:
user --n:1--> reservation <--1:n-- concert
so pseudo-code:
reservation belongs_to user reservation belongs_to concert user has_many reservations user has_many concerts through reservations concert has_many reservations concert has_many users through reservations
how make single big array of everything?
- i can reservations via
reservation.all
- i can user particular reservation via
reservation.find(25).user
- i can concert particular reservation via
reservation.find(25).concert
but how of them? if do
reservation.all.each |res| res.user.name+","+res.concert.name+","+res.concert.date # etc. end
then 2 new database queries each reservation loops through. 10 records, might not matter, thousands, can painful. add other associations (e.g. concert belongs_to venue, user has_one email, etc.)...
is there way say, "get of reservations , following attached info" loads in single sql query?
what you're trying accomplish called eager loading, , can done using includes
in activerecord
. see below:
n + 1 queries problem
active record lets specify in advance associations going loaded. possible specifying includes method of model.find call. includes, active record ensures of specified associations loaded using minimum possible number of queries.
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
in example use following:
reservation.all.includes(:user, :concert)
it idea specify :inverse_of
option :belongs_to
relations. optimizes object loading , makes sure cross-referencing model point same object in memory, i.e.:
@user == @user.reservations.first.user # true
more information available here:
if using belongs_to on join model, idea set :inverse_of option on belongs_to ...
http://api.rubyonrails.org/classes/activerecord/associations/classmethods.html
in example:
# app/models/reservation.rb belongs_to :user, :inverse_of => :reservations belongs_to :concert, :inverse_of => :reservations
Comments
Post a Comment