2012年6月18日月曜日

同じテーブルを参照するactiverecord

クラス名と外部キー名を設定出来ます。


# Create models:
rails g model location name:string
rails g model route

# Add associations between models:
in Location, add:
    has_many :routes

in Route, add:
    belongs_to :location_start, :class_name => Location, :foreign_key
=> "location_start_id"
    belongs_to :location_end, :class_name => Location, :foreign_key
=> "location_end_id"

# Define foreign keys in db migration:

class CreateRoutes < ActiveRecord::Migration
 def change
   create_table :routes do |t|
     t.references :location_start
     t.references :location_end

     t.timestamps
   end
 end
end

# Now in console:
munich = Location.new
munich.name = "Munich"; munich.save!

tokyo = Location.new
tokyo.name = "Tokyo"; tokyo.save!

route = Route.new
route.location_start = munich
route.location_end = tokyo
route.save!

0 件のコメント:

コメントを投稿