I have a simple association like
class Slot < ActiveRecord::Base
has_many :media_items, dependent: :destroy
end
class MediaItem < ActiveRecord::Base
belongs_to :slot
end
The MediaItems
are ordered per Slot
and have a field called ordering
.
And want to avoid n+1 querying but nothing I tried works. I had read several blogposts, railscasts etc but hmm.. they never operate on a single model and so on...
What I do is:
def update
@slot = Slot.find(params.require(:id))
media_items = @slot.media_items
par = params[:ordering_media]
# TODO: IMP remove n+1 query
par.each do |item|
item_id = item[:media_item_id]
item_order = item[:ordering]
media_items.find(item_id).update(ordering: item_order)
end
@slot.save
end
params[:ordering_media]
is a json array with media_item_id
and an integer for ordering
I tried things like
@slot = Slot.includes(:media_items).find(params.require(:id)) # still n+1
@slot = Slot.find(params.require(:id)).includes(:media_items) # not working at all b/c is a Slot already
media_items = @slot.media_items.to_a # looks good but then in the array of MediaItems it is difficult to retrieve the right instance in my loop
This seems like a common thing to do, so I think there is a simple approach to solve this. Would be great to learn about it.