简体   繁体   English

渴望加载多态关联

[英]Eager loading with polymorphic associations

I have three models: 我有三种模式:

User.rb
belongs_to :profile, polymorphic: true

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

Sale.rb
belongs_to :customer

I want to pull all the sales with the emails of the customer which is stored in the user model. 我想通过存储在用户模型中的客户电子邮件来拉动所有销售额。 What is the best way to do this? 做这个的最好方式是什么?

So far, I just have the following: 到目前为止,我只有以下内容:

Sale.all.includes(:customer)

You can do it as: 您可以按照以下方式进行操作:

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

It will get all the sales records with their customer and profiles nested into them and you can use it on the Sale object as: 它将获得所有销售记录及其客户和配置文件,它们嵌套在其中,您可以按以下方式在Sale对象上使用它:

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

Though, I think it would be a costly method as I can see there will be 3 SQL queries in total to get all the records and 2 of them are using IN () that has significant cost I guess. 但是,我认为这将是一种昂贵的方法,因为我可以看到总共有3条SQL查询来获取所有记录,其中2条正在使用IN () ,我猜这会花费很多。 So we shall better go with the LEFT JOIN in that case. 因此,在这种情况下,我们最好采用LEFT JOIN。

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

This query will get all the sales records with the nested user profiles without customer data/records. 该查询将获得所有带有嵌套用户资料的销售记录,而没有客户数据/记录。 In case you need the customer data too, you can always go with this: 如果您也需要客户数据,则可以始终这样做:

@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