【问题标题】:ActiveRecord :inverse_of does not work on has_many :through on the join model on createActiveRecord :inverse_of 不适用于 has_many :through 在创建时的连接模型上
【发布时间】:2011-09-15 19:12:02
【问题描述】:

我无法让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_ids 是我的challenge 的虚拟属性,我想在创建该关联时在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 的设计限制还是实现中的错误?

【问题讨论】:

  • 我也有同样的问题。

标签: ruby-on-rails activerecord associations


【解决方案1】:

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

【讨论】:

  • 哦,很好,我从来没有注意到那个文档。太糟糕了,它会很方便!!
猜你喜欢
  • 1970-01-01
  • 2011-02-16
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多