1
 class CreateTestings < ActiveRecord::Migration
  def self.up
    create_table :testings do |t|
      t.string "name"
      t.boolean "visible"
      t.string "description"
      t.integer "roll"
      t.references "students"
      t.timestamps
    end
  end

  def self.down
     drop_table :testings
  end
end

Hello, i just ran this test migration to see how Rails handles Migrations. Even though i have t.references "students"

Rails created the students_id in my testings table successfully but however didn't specified any foreign key on it:

mysql> DESC testings;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | YES  |     | NULL    |                |
| visible     | tinyint(1)   | YES  |     | NULL    |                |
| description | varchar(255) | YES  |     | NULL    |                |
| roll        | int(11)      | YES  |     | NULL    |                |
| students_id | int(11)      | YES  |     | NULL    |                |
| created_at  | datetime     | YES  |     | NULL    |                |
| updated_at  | datetime     | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

Is this how Rails works or otherwise i should've had

t.references :student instead of t.references "students"

Thanks!

1 Answer 1

2

This is how rails works. It doesn't specify foreign key dependencies in its migrations. You'll have to do this manually with an 'execute' command and SQL code if you do want to specify foreign-key dependencies.

2
  • That depends on your business needs and if you want to duplicate these constraints in your database layer. Your application will function properly and transactions will work as intended in mysql even without the foreign key dependency. Feb 1, 2011 at 4:08
  • +1 this is just how Rails works. See this paragraph of the Rails guides for a bit of an explanation: Active Record and Referential Integrity. Feb 1, 2011 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.