【问题标题】:rails HABTM to has many throughrails HABTM 有很多通过
【发布时间】: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_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

【问题讨论】:

  • 在请别人为您做之前,请展示您自己尝试过的内容。
  • 我在玩类名和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


【解决方案1】:

即使在编辑模型之后,也有必要创建一个新的连接表,因为前一个连接表(由 habtm 创建)没有“id”列。 作为参考,您可以按照http://www.chrisrolle.com/en/blog/migration-path-from-habtm-to-has_many-through中指示的步骤进行操作

【讨论】:

    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 2021-11-16
    • 2023-04-09
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多