【发布时间】:2017-04-25 20:56:53
【问题描述】:
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_id 和question_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
【问题讨论】:
-
在请别人为您做之前,请展示您自己尝试过的内容。
-
我在玩类名和foreign_key。但没有什么对我有用
-
更新了我的问题,请看一下
-
我要的是数据库架构。你可以在这里找到它:
db/schema.rb -
create_table "question_question_sets", force: :cascade do |t| t.integer "question_id" t.integer "question_set_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
标签: ruby-on-rails has-many-through has-and-belongs-to-many single-table-inheritance sti