ruby - Best way to get records from another model again and again - Rails -


i have model booking contains space_id attributes associated space model belongs_to :space.

now have multiple spaces , want count each booking respect every id.

i want best way fatch records db without fire query again , again. currently, i'm doing this:

spaces = space.all result = [] spaces.each |s|     result << s.as_json.merge(:bookings_counts=>s.bookings.count) end 

but firing query again , again form db. there best way this?

this called "n+1 queries" problem. in rails can use eager loading resolve it. use includes load records in single query changing first line of code to

spaces = space.eager_load(:bookings) 

here explanation , comparison of ways (includes, eager_load , preload) eager loading in rails link.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -