ActiveRecord:inverse_of不适用于has_many:通过on上的连接模型

bra*_*rad 6 activerecord ruby-on-rails associations

我无法inverse_of在创建时加入联合模型.我不确定这是一个错误还是没有实现.我有以下型号:

class Challenge < ActiveRecord::Base
  has_many :groups, :through => :group_challenges
  has_many :group_challenges, :inverse_of => :challenge

  attr_accessor :contact_ids
end

class GroupChallenge < ActiveRecord::Base
  belongs_to :challenge, :inverse_of => :group_challenges
  belongs_to :group, :inverse_of => :group_challenges

  before_save :check_challenge

  def check_challenge
    Rails.logger.debug("challenge.contact_ids: #{challenge.contact_ids}")
  end
end

class Group < ActiveRecord::Base
  has_many :challenges, :through => :group_challenges
  has_many :group_challenges, :inverse_of => :group
end
Run Code Online (Sandbox Code Playgroud)

contact_ids是我的虚拟属性challenge,我想在group_challenges创建该关联时在模型中访问这些属性.我无法让它发挥作用.这是一个例子:

challenge = Challenge.new :groups => Group.all, :contact_ids => [1,2,3]
# log output => challenge.contact_ids: []
Run Code Online (Sandbox Code Playgroud)

inverse_of重新加载模型时可行

challenge.reload
challenge.group_challenges.first.challenge.contact_ids
# log output => challenge.contact_ids: [1,2,3]
Run Code Online (Sandbox Code Playgroud)

有谁知道这只是inverse_of的设计限制,还是实现中的错误?

小智 17

根据活动记录api 3.2.1:"当前:inverse_of支持has_one和has_many(但不支持:through variants)关联.它还为belongs_to关联提供反向支持,其中inverse是has_one,而不是多态."

  • 哦,好的,我从来没有注意到那些文件.太糟糕了,它会很方便!! (2认同)