mardi 25 juillet 2017

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

I have a model Booking which contains space_id attributes associated with Space Model by belongs_to :space.

Now I have multiple spaces and want to count each booking with respect to every id.

I want to get the best way to fatch records from DB without fire query again and again. Currently, I'm doing like this:

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

but this is firing query again and again form db. is there any best way to do this?

Aucun commentaire:

Enregistrer un commentaire