rails HABTM有很多通过

时间:2016-12-10 13:56:33

标签: ruby-on-rails has-many-through has-and-belongs-to-many single-table-inheritance sti

class QuestionSet
  has_and_belongs_to_many :questions,
                      class_name: 'Exam',
                      join_table: 'question_question_sets',
                      foreign_key: 'question_set_id',
                      association_foreign_key: 'question_id'

end

class Question
  has_and_belongs_to_many :question_sets,
                      class_name: 'Exam',
                      join_table: 'question_question_sets',
                      foreign_key: 'question_id',
                      association_foreign_key: 'question_set_id'

end

以上模型继承自基础模型Exam(使用rails STI),连接表包含两个字段:question_idquestion_set_id。现在我需要将此关联转换为has_many through

我尝试过如下:

class QuestionQuestionSet
  has_many :questions
  has_many :question_sets 
end

class Question
  has_many :question_question_sets, foreign_key: :question_id
  has_many :question_sets, through: :question_question_sets 
end

class QuestionSet
  has_many :question_question_sets, foreign_key: :question_set_id
  has_many :questions, through: :question_question_sets 
end

1 个答案:

答案 0 :(得分:2)

即使在编辑模型之后,创建新的连接表也是必要的,因为前一个(由habtm创建)并没有" id"柱。 作为参考,您可以按照http://www.chrisrolle.com/en/blog/migration-path-from-habtm-to-has_many-through

中指示的步骤操作