05
APR
Migrations in Rails
Posted by Adam Posted in Programming 0 comments
This post is follow on from a recent post of mine on RailsForums and it outlines some of the slightly more advanced methods of using migrations in rails.
Foreign Keys
You can’t directly set foriegn keys with migrations (yet), although you can add a SQL command to a migration for FK using:
execute "alter table table_name add constraint fk_name_of_fk /
foreign key (field_name) references foriegn_table(id)<
There is a plugin which handles this fully if you need it. Here.
Primary Keys
Primary Keys can be set using:
create_table :table_name, :primary_key => "field_name"
You simply need to add the primary_key to the create_table call. Rails by default will add an id field as the primary key. This option overrides that primary key.
If you change your primary key don’t forget to tell your model about the new one using self.primary_key = “whatever"
NOT NULL
t.column :field_name, :type, :null => false
This should be specified in your model using validates_presence_of as well
Unique
Unique should really be handed within your model rather than at a SQL level – using validates_uniqueness_of inside the model.
Comments
Add a Comment
No comments yet... :(