2010-08-18 39 views
0

我對軌道有點新,所以如果這是非常基本的請耐心等待。我如何在Rails中模擬這種關係

我正在創建類似聊天應用程序的東西。我的模型看起來像這樣(從schema.rb)

create_table "people", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "session_id" 
end 

create_table "sessions", :force => true do |t| 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "leader_id" 
end 

我已經設置了我想要的基本關係 - 這是SESSION_ID是在人民表的外鍵這樣:

class Person < ActiveRecord::Base 
belongs_to :session 
end 

class Session < ActiveRecord::Base 
has_many :people 
end 

我希望leader_id現在成爲會話的「主持人」(因此,它恰好是一個人的外鍵)。如何建立一個額外的關聯,所以我可以做的:

session = Session.find_by_id(1) 
host = Person.new(:name => 'joebob') 
session.leader = host 
+0

你可能想重命名你的會話,這是ror的保留字如果我沒有弄錯 – corroded 2010-08-18 06:27:45

+0

啊好建議我會重新命名它。謝謝! – Ish 2010-08-18 06:57:28

回答

1

你可以告訴Rails該leader_id確實是一個人的ID通過在belongs_to的關聯指定類名:

class Session < ActiveRecord::Base 
    belongs_to :leader, :class_name => "Person" 
end 
+0

哇像一個魅力工作。謝謝!!!我想belongs_to總是意味着'爲這個模型添加一個外鍵' – Ish 2010-08-18 06:56:17