在mongoid中将相同的模型关联两次

时间:2017-02-28 04:57:58

标签: ruby-on-rails ruby-on-rails-4 mongoid

我有两个课程Intern::QuestionIntern::Answer,标准关联如下:

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

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

现在我想引用两次回答belongs_to问题,回答可以存储父问题和下一个问题,如:

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

但我已经尝试过并收到此错误:

Mongoid::Errors::AmbiguousRelationship

1 个答案:

答案 0 :(得分:0)

使用inverse_of

找到解决方案here
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