简体   繁体   中英

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:

@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. So we shall better go with the LEFT JOIN in that case.

@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"')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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