简体   繁体   English

Rails:为has_many和has_one创建迁移

[英]Rails: Create migrations for has_many and has_one

I have Question , Option and Answer models as follows: 我有QuestionOptionAnswer模型,如下所示:

class Question < ApplicationRecord
  belongs_to :user
  has_many :options
  has_one :answer
end

class Option < ApplicationRecord
  belongs_to :question
  has_many :answers
end

class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :option
end

I have one migration files for Question and Option models like this: 我有一个用于QuestionOption模型的迁移文件,如下所示:

class CreateQuestions < ActiveRecord::Migration[5.2]
  def change
    create_table :questions do |t|
      t.text :body
      t.references :user, foreign_key: true

      t.timestamps
    end
  end
end

class CreateOptions < ActiveRecord::Migration[5.2]
  def change
    create_table :options do |t|
      t.references :question, foreign_key: true

      t.timestamps
    end
  end
end

If my understanding is correct, I have a migration here for belongs_to association. 如果我的理解是正确的,那么我将在这里进行一个belongs_to关联的迁移。 My doubt is, are these migration files enough to create has_many associations or do I need to add any extra conditions in migrations files? 我的疑问是,这些迁移文件是否足以创建has_many关联,还是需要在migrations文件中添加任何其他条件? If yes, please tell me what to add. 如果是,请告诉我要添加的内容。 I referred the following link: [ Rails survey style application - Show all answers on option 我引用了以下链接:[ Rails调查样式应用程序-显示选项的所有答案

[1]: https://https://stackoverflow.com/questions/35771847/rails-survey-style-application-show-all-answers-on-option but I did not understand whether I need to add extra line for has_many and has_one associations. [1]: https:// https://stackoverflow.com/questions/35771847/rails-survey-style-application-show-all-answers-on-option,但是我不知道是否需要为has_manyhas_one关联。

Your migrations are correct, because if you think of your models as in database tables, you will never store the 'has_many' option somewhere. 您的迁移是正确的,因为如果您将模型视为数据库表中的模型,则永远不会将“ has_many”选项存储在某处。 That is merely for the human understanding, as well as for ActiveRecord. 那只是为了人类的理解,也是为了ActiveRecord。 So an option in your example belongs to a question, hence we have to store the ID of that question in the record of the answer. 因此,您的示例中的一个选项属于一个问题,因此我们必须将该问题的ID存储在答案的记录中。 In the question migration however, we don't store any information regarding the option, it is enough that the option "knows" which question it belongs to. 但是,在问题迁移中,我们不存储有关选项的任何信息,选项“知道”它属于哪个问题就足够了。 (And same for user and question). (与用户和问题相同)。

Only in the model you can then specify - as you did - the 'has_many' options. 然后,只有在模型中,您才可以指定-has_many选项。 This will allow you later to call 'question.options` to retrieve all options that belong to a question. 这将使您以后可以调用“ question.options”来检索属于问题的所有选项。

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

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