ActiveRecord :inverse_of 不适用于 has_many :through 在创建时的连接模型上 [英] ActiveRecord :inverse_of does not work on has_many :through on the join model on create
问题描述
我无法让 inverse_of
在创建时处理连接模型.我不确定这是一个错误还是只是没有实现.我有以下型号:
课程挑战:group_challengeshas_many :group_challenges, :inverse_of =>:挑战attr_accessor :contact_ids结尾class GroupChallenge :group_challenges所属:组,:inverse_of =>:group_challengesbefore_save :check_challengedef check_challengeRails.logger.debug("challenge.contact_ids: #{challenge.contact_ids}")结尾结尾班级组:group_challengeshas_many :group_challenges, :inverse_of =>:团体结尾
contact_ids
是我的 challenge
的虚拟属性,我想在创建关联时在 group_challenges
模型中访问这些.我无法让它工作.举个例子:
challenge = Challenge.new :groups =>Group.all, :contact_ids =>[1,2,3]# 日志输出 =>Challenge.contact_ids: []
但是 inverse_of
在模型重新加载时确实有效
challenge.reloadChallenge.group_challenges.first.challenge.contact_ids# 日志输出 =>Challenge.contact_ids: [1,2,3]
有谁知道这只是 inverse_of 的设计限制还是实现中的错误?
根据 活动记录 api 3.2.../p>
I can't get inverse_of
to work on join models on creation. I'm not sure if this is a bug or just not implemented as such. I have the following models:
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
contact_ids
is a virtual attribute of my challenge
, and I'd like to access these in the group_challenges
model when that association is created. I can't get it to work. Here's an example:
challenge = Challenge.new :groups => Group.all, :contact_ids => [1,2,3]
# log output => challenge.contact_ids: []
However inverse_of
does work when the models are reloaded
challenge.reload
challenge.group_challenges.first.challenge.contact_ids
# log output => challenge.contact_ids: [1,2,3]
Does anyone know if this is just a design limitation of inverse_of or rather a bug in the implementation?
As per the active record api 3.2.1: "Currently :inverse_of supports has_one and has_many (but not the :through variants) associations. It also supplies inverse support for belongs_to associations where the inverse is a has_one and it’s not a polymorphic."
这篇关于ActiveRecord :inverse_of 不适用于 has_many :through 在创建时的连接模型上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!