itx
itx

Reputation: 1409

Associates the same model twice in mongoid

I have two class Intern::Question and Intern::Answer, and the standard association look like :

class Intern::Question
  has_many :intern_answers, class_name: 'Intern::Answer'
end

class Intern::Answer
  belongs_to :intern_question, class_name: 'Intern::Question'
end

And now I want to reference twice answer belongs_to question, answer can store parent question and next question, something like :

class Intern::Question
  has_many :intern_answers, class_name: 'Intern::Answer'
  has_many :node_for_answers, class_name: 'Intern::Answer'
end

class Intern::Answer
  belongs_to :intern_question, foreign_key: :intern_question_id, class_name: 'Intern::Question'
  belongs_to :next_question, foreign_key: :next_question_id, class_name: 'Intern::Question'
end

But I have try that and get this error :

Mongoid::Errors::AmbiguousRelationship

Upvotes: 0

Views: 189

Answers (1)

itx
itx

Reputation: 1409

Found solution here, using inverse_of

class Intern::Question
  has_many :intern_answers, class_name: 'Intern::Answer', inverse_of: :intern_question
  has_many :node_for_answers, class_name: 'Intern::Answer', inverse_of: :next_question
end

class Intern::Answer
  belongs_to :intern_question, foreign_key: :intern_question_id, class_name: 'Intern::Question', inverse_of: :intern_answers
  belongs_to :next_question, foreign_key: :next_question_id, class_name: 'Intern::Question', inverse_of: :node_for_answers
end

Upvotes: 1

Related Questions