Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...