简体   繁体   中英

Rails: Create migrations for has_many and has_one

I have Question , Option and Answer models as follows:

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:

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. 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? If yes, please tell me what to add. I referred the following link: [ Rails survey style application - Show all answers on option

[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.

Your migrations are correct, because if you think of your models as in database tables, you will never store the 'has_many' option somewhere. That is merely for the human understanding, as well as for 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. 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. This will allow you later to call 'question.options` to retrieve all options that belong to a question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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