rails HABTM to has many through


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

即使在编辑模型后,也必须创建一个新的加入表,因为上一个(由HABTM创建)没有和" ID"列。作为参考,您可以按照http://www.chrisrolle.com/en/blog/migration-path-path-from-habtm-habtm-to-has_many-though

中指定的步骤。

相关内容

  • 没有找到相关文章

最新更新