2
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. Now I need to convert this association into 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
Vijith mv
  • 404
  • 7
  • 22

1 Answers1

2

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. As a reference you can follow the steps indicated in http://www.chrisrolle.com/en/blog/migration-path-from-habtm-to-has_many-through

crestor
  • 1,388
  • 8
  • 21