I'm making a quiz app with Ruby on Rails where I have a model "Answer". Now I need to save the answer a user gives for a question to the database, so I thought I'll make a model "GivenAnswer" and matching controller with these existing models as attributes:
"User"
"Question"
"Answer"
I'm going to put all the logic for analyzing the given answers into the "GivenAnswers" controller, but am not sure how the db migration should look. Also, I would like to have indexes on "User" and "Question", since I'm going to frequently display "answers per user" and "answers per question". I generated this migration:
class CreateGivenAnswers < ActiveRecord::Migration[5.0]
def change
create_table :given_answers do |t|
t.references :user, foreign_key: true
t.references :question, foreign_key: true
t.references :answer, foreign_key: true
t.timestamps
end
end
end
But I'm wondering if the table should be purely relational instead:
class CreateGivenAnswers < ActiveRecord::Migration[5.0]
def change
create_table :given_answers, id:false do |t|
t.belongs_to :user, index: true
t.belongs_to :question, index: true
t.belongs_to :answer
end
end
end
I'm a Rails beginner, so I'd be thankful for any pointers.
belongs_to
is an alias for references
so it makes no difference which of those you use.
Don't remove the id column in this case.
Any foreign key should also be an index.
I would do this:
class CreateGivenAnswers < ActiveRecord::Migration[5.0]
def change
create_table :given_answers, id:false do |t|
t.references :user, index: true, foreign_key: true
t.references :question, index: true, foreign_key: true
t.references :answer, index: true, foreign_key: true
end
end
end
But I don't think that you should relate Answer
directly to GivenAnswer
. It would make more sense to relate Answer
to Question