Rails 4 - eager loading on dependent select causing error (Rails4/Active Admin)
When you call ActiveRecord::find
– it means you are expecting to get a one, single model from the DB.Then, you referring to this model and call dealsubsectors
– I assume it's has_many
relation to your model. It will produce 2 queries: first to fetch original DealSelector
, second – all related DealSubsectors
.There's nothing you can optimise (unless you dealsubsectors
is a custom method in your model, not the relation).
If you see that something hits your DB with queries – you have to look in another place. Say, your form – do you display only one Client per form? If not, it will iterate and fetch all DealSector and DealSubsector again for every new client. Try to provide more code.
Rails 4 comes with some changes with respect to eager load algorithm.you can try the below code snippets in your case:
@deal_subsectors = DealSector.eager_load(:deal_subsectors).find(params[:deal_sector_id]).dealsubsectors
or
@deal_subsectors = DealSector.includes(:deal_subsectors).find(params[:deal_sector_id]).dealsubsectors
first one will fetch the data in single query but second one will make two query.
Why can't you just fetch the all DealSubsector records for the given the sector_id
?
DealSubsector.where(deal_sector_id: params[:deal_sector_id])