简体   繁体   English

rails HABTM有很多通过

[英]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

The above models are inherited from the base model Exam (using rails STI) and the join table contains two fields: question_id and question_set_id . 以上模型继承自基本模型Exam (使用rails STI),连接表包含两个字段: question_idquestion_set_id Now I need to convert this association into has_many through . 现在我需要将此关联转换为has_many through

I have tried as follows: 我试过如下:

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

Even after editing your models, it's necessary to create a new join table since the previous one (created by habtm) doesn't have and "id" column. 即使在编辑模型之后,也需要创建一个新的连接表,因为前一个(由habtm创建)没有和“id”列。 As a reference you can follow the steps indicated in http://www.chrisrolle.com/en/blog/migration-path-from-habtm-to-has_many-through 作为参考,您可以按照http://www.chrisrolle.com/en/blog/migration-path-from-habtm-to-has_many-through中指示的步骤进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM