How to specify eager loading of associations in rails model

只愿长相守 提交于 2019-12-12 03:30:01

问题


class A < ActiveRecord::Base
  has_many :Bs
  has_many :Cs
  ...
end

I wish to load all of B's and C's whenever I do a query on A, say A.where(name: :abc), with a single query, instead of multiple calls to database.

I don't wish to specify .includes for every query I run. How do I specify eager loading in the model itself?

I looked many similar question and tried do this but it does not work:

default_scope :include => [:Bs, :Cs]

回答1:


default_scope { includes(:Bs, :Cs) } should do it.

As far as I know the scope takes a block as argument not a hash of options. I just tried it in the rails console and seems to work.



来源:https://stackoverflow.com/questions/35374387/how-to-specify-eager-loading-of-associations-in-rails-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!