Forum: Ruby on Rails Active Record Migrations -> Table Relations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6a6e2099a116620e0b4bad749cd41458?d=identicon&s=25 Bernhard Glück (Guest)
on 2006-05-22 03:11
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
A0c079a7c3c9b2cf0bffebd84dc578b0?d=identicon&s=25 unknown (Guest)
on 2006-05-22 03:41
(Received via mailing list)
On May 21, 2006, at 8:11 PM, Bernhard Glück wrote:

> 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/UsingMigra...
Rails mailing list
Rails@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails
This topic is locked and can not be replied to.