Migrations Without belongs_to Or references

Normally when do a database migration in Rails, when adding ownership from a model to another model, you use the concept of belongs_to or references:

  create_table :comments do |t|
    t.belongs_to :user
    t.references :post

Interestingly enough, these methods are only available during the initial table creation. If you want to add a reference to a model that is created later, you have to do it the old fashioned way, by just adding a column:

   add_column :comments, :group_id, :integer

Doing it this way is clean, easy, and definitely meets the KISS principle. But I do find it interesting that one can’t add an association later in the game. Sometimes the Rails way is just KISS and adding the column by hand.

Posted in Rails. Tags: . No Comments »