[英]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.