繁体   English   中英

渴望加载多态关联

[英]Eager loading with polymorphic associations

我有三种模式:

User.rb
belongs_to :profile, polymorphic: true

Customer.rb
has_one :user, as: :profile, dependent: :destroy

Sale.rb
belongs_to :customer

我想通过存储在用户模型中的客户电子邮件来拉动所有销售额。 做这个的最好方式是什么?

到目前为止,我只有以下内容:

Sale.all.includes(:customer)

您可以按照以下方式进行操作:

@sales = Sale.includes(:customer => :user).all

它将获得所有销售记录及其客户和配置文件,它们嵌套在其中,您可以按以下方式在Sale对象上使用它:

@sales.first.customer.user.email #get the email for first Sale record.

但是,我认为这将是一种昂贵的方法,因为我可以看到总共有3条SQL查询来获取所有记录,其中2条正在使用IN () ,我猜这会花费很多。 因此,在这种情况下,我们最好采用LEFT JOIN。

@sales = Sale.joins('LEFT JOIN users ON sales.customer_id = users.profile_id AND users.profile_type = "Customer"')

该查询将获得所有带有嵌套用户资料的销售记录,而没有客户数据/记录。 如果您也需要客户数据,则可以始终这样做:

@sales = Sale.joins('LEFT JOIN customers ON sales.customer_id = customers.id LEFT JOIN users ON customers.id = users.profile_id AND users.profile_type = "Customer"')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM