Reputation: 1139
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:
[https://stackoverflow.com/questions/35771847/rails-survey-style-application-show-all-answers-on-option][1]
[1]: 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.
Upvotes: 0
Views: 609
Reputation: 2715
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.
Upvotes: 1