本文介绍了我可以添加一个包括延伸到belongs_to的关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法得到一个 belongs_to的协会贪婪加载它的孩子。我有:

I'm having trouble getting a belongs_to association to eager load it's children. I have:

class User < ActiveRecord::Base
  has_many   :campaigns, -> { includes :campaign_shirts, :arts, :selected_campaign_shirt }
  belongs_to :selected_campaign, {class_name: "Campaign", inverse_of: :user}, -> { includes :campaign_shirts, :arts, :selected_campaign_shirt }
end

这会导致:

// GOOD
u.campaigns.first.campaign_shirts.first.to_s
=> "#<CampaignShirt:0x007fc023a9abb0>"
u.campaigns.first.campaign_shirts.first.to_s
=> "#<CampaignShirt:0x007fc023a9abb0>"

// NOT GOOD
u.selected_campaign.campaign_shirts.first.to_s
(queries db)
=> "#<CampaignShirt:0x007fc023d7c630>"
(queries db)
u.selected_campaign.campaign_shirts.first.to_s
=> "#<CampaignShirt:0x007fc01af528a0>"

我正在运行相抵触这个问题?有没有一种方法可以达到我想要的,这是为了能够参照 current_user.selected_campaign 并渴望加载/冷冻 current_user.selected_campaign .campaign_shirts.first 等。?

Am I running afoul of this issue? Is there a way to achieve what I want, which is to be able to refer to current_user.selected_campaign and have eager-loaded/frozen current_user.selected_campaign.campaign_shirts.first etc.?

推荐答案

尝试将拉姆达范围内先于其他关联选项喜欢如下:

Try moving the lambda scope before other association options like follows:

# app/models/users.rb

belongs_to :selected_campaign, -> { includes :campaign_shirts, :arts, :selected_campaign_shirt }, {class_name: "Campaign", inverse_of: :user}, 

这篇关于我可以添加一个包括延伸到belongs_to的关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:07