Monday, 26 August 2013

Possible to add a column to an ActiveRecord model that is a foreign key?

Possible to add a column to an ActiveRecord model that is a foreign key?

I can easily create a scaffold or model in Rails with a field that is a
reference (foreign key) to another model:
rails g model Cat owner:references
rails g scaffold Cat owner:references
But I can't seem to do the same for adding a column in a migration:
rails g migration AddOwnerToCats owner:references
What the above does is produce a migration file like this:
class AddOwnerToCats < ActiveRecord::Migration
def change
add_column :cats, :owner, :references
end
end
And when I try and run it with rake db:migrate, I get this:
SQLite3::SQLException: near "references": syntax error: ALTER TABLE "cats"
ADD "owner" references
So is there a way to add a column that is a reference to another model? Or
do I just have to do:
rails g migration AddOwnerToCats owner_id:integer
And then go into the migration and add an index for owner_id?

No comments:

Post a Comment