Reputation: 2693
I realized that I managed to generate a model improperly and am having trouble "rollingback" the mistake. I was generating a model to contain questions for a parent form, writing it as follows:
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.integer :legalform_id
t.integer :question_number
t.string :type
t.text :the_question
t.timestamps
end
end
end
and then running rake db:migrate
to generate the relevant tables.
The attribute legalform_id
was to contain the id of the parent form to which the question was associated. ...I then learned about rails and associations, realizing that what I was attempting to do was baked into the framework. So I changed the legalform_id
line, so that the migration table read like this:
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.references :legalform
t.integer :question_number
t.string :type
t.text :the_question
t.timestamps
end
end
end
I entered the command rake db:rollback
which dropped the questions table and then ran rake db:migrate
, assuming that the change I'd made to the migration table would generate the mysql table accordingly. Much to my surprise, the new table contained the same attributes as specified by the original migration table reading as follows:
mysql> show columns in questions;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| legalform_id | int(11) | YES | | NULL | |
| question_number | int(11) | YES | | NULL | |
| type | varchar(255) | YES | | NULL | |
| the_question | text | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
What might be the cause of this? Am I missing something? Many thanks for any guidance.
Upvotes: 0
Views: 43
Reputation: 7307
references
also creates the same foreign key constraints, in your case legalform_id
, the difference between using references
vs legalform_id
is that when using references
it will automatically add appropriate relationship definitions in the models and also add index for the field
Upvotes: 0
Reputation: 5732
This is exactly what you want. It creates the same column, while adding an index as well. add_reference
creates the column with the name you specified, which in your case is the same as the original migration. If you run SHOW INDEXES
on the table, you should see the newly created index as well.
Upvotes: 2