Hi there ! I am currently investingation ROR. I really like the idea of specifying my database schema via Migrations, but one questions came to my mind. How does one specify Table relations in the migration ? 1. There is a fancy way of doing it with Active Records. 2. I just add manually some Integer ID columns etc... and lateron add the Foreign Key semantic via SQL.. Which one of the above holds true ? I was not able to find anythign in the documentation about it... Thanks -- Posted via http://www.ruby-forum.com/.
cremes.devlist@mac.com
2006-May-22 01:39 UTC
[Rails] Active Record Migrations -> Table Relations
On May 21, 2006, at 8:11 PM, Bernhard Gl?ck wrote:> Hi there ! > > I am currently investingation ROR. > I really like the idea of specifying my database schema via > Migrations, > but one questions came to my mind. > > How does one specify Table relations in the migration ? > > 1. There is a fancy way of doing it with Active Records. > 2. I just add manually some Integer ID columns etc... and lateron add > the Foreign Key semantic via SQL.. > > > Which one of the above holds true ? I was not able to find anythign in > the documentation about it...You add the foreign_key right there in the migration. For example, let''s say you have User and Item models that are related. User has a one-to-many relationship with Item. class AddTableRelation < ActiveRecord::Migration def self.up create_table :users do |t| t.column :title, :string, :limit => 255 end create_table :items do |t| t.column :title, :string, :limit => 255 t.column :user_id, :integer end end def self.down drop_table :users drop_table :items end end In your model definitions for User and Item you also need to specify the relationship. In User you specify a "has_many :items" and in Item you specify "belongs_to :user". If you want the database engine to enforce the foreign key relationship, there is no direct ActiveRecord Migration support for that functionality. You need to specify it using the "execute" syntax. Some enterprising folks have added plugins that add foreign key methods to the migration facility but they are not a standard part of Rails. I highly recommend taking a look at the UsingMigrations wiki page [1] for more information. cr [1] http://wiki.rubyonrails.com/rails/pages/UsingMigrations