如何在Rails模型中指定关联的紧急加载 [英] How to specify eager loading of associations in rails model

查看:86
本文介绍了如何在Rails模型中指定关联的紧急加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我希望在每次对A进行查询时都加载所有B和C,例如 A.where(name::abc)

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.

我不希望为 .includes 指定一个查询我运行的每个查询。我如何在模型本身中指定急切的加载?

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]


推荐答案

default_scope {includes(:Bs,:Cs)} 应该这样做。

据我所知,作用域采用一个块作为参数不是选项的哈希。我只是在Rails控制台中尝试过,似乎可以正常工作。

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.

这篇关于如何在Rails模型中指定关联的紧急加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆