我可以为belongs_to关联添加包含扩展名吗?

时间:2013-11-21 21:32:09

标签: ruby-on-rails activerecord

我无法获得belongs_to关联以急切加载它的孩子。我有:

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

我是否与this issue发生冲突?有没有办法实现我想要的,哪些是能够引用current_user.selected_campaign并且有急切加载/冻结current_user.selected_campaign.campaign_shirts.first等等?

1 个答案:

答案 0 :(得分:1)

尝试在其他关联选项之前移动lambda范围,如下所示:

# app/models/users.rb

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