can I add an includes extension to a belongs_to association?

微笑、不失礼 提交于 2019-12-11 20:17:50

问题


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

which results in:

// 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>"

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.?


回答1:


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}, 


来源:https://stackoverflow.com/questions/20132350/can-i-add-an-includes-extension-to-a-belongs-to-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!