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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -