gpt4 book ai didi

ruby-on-rails - ActiveRecord :inverse_of does not work on has_many :through on the join model on create

转载 作者:行者123 更新时间:2023-12-04 13:14:40 26 4
gpt4 key购买 nike

我无法在创建时让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
contact_idschallenge的虚拟属性,创建关联后,我想在 group_challenges模型中访问这些属性。我无法正常工作。这是一个例子:
challenge = Challenge.new :groups => Group.all, :contact_ids => [1,2,3]
# log output => challenge.contact_ids: []

但是,当重新加载模型时, inverse_of可以工作
challenge.reload
challenge.group_challenges.first.challenge.contact_ids
# log output => challenge.contact_ids: [1,2,3]

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

最佳答案

按照active record api 3.2.1:“当前:inverse_of支持has_one和has_many(但不支持:through变体)关联。它还为反向为has_one而不是多态的belongs_to关联提供反向支持。”

关于ruby-on-rails - ActiveRecord :inverse_of does not work on has_many :through on the join model on create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7436173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com