2011-01-27 127 views
2

I「M樓一個Rails應用程序,並且有兩種模式,我想連接。鏈接模型在Ruby on Rails的

有一個叫做模型‘用戶’是處理用戶身份驗證,如用戶名和密碼數據。然後有一個名爲「個人資料」的模型,其中包含一個人的位置,描述等等。

我想鏈接模型,以便每個用戶有一個配置文件,我真的不知道該怎麼做。分享一些見解,如何做到這一點?

回答

4

看看rails associations basics

您asociation看起來就像

class User < AR:Base 
    has_one :profile 
end 

class Profile < AR:Base 
    belongs_to :user 
end 

哦,表型材必須與外鍵用戶user_id列。

+0

謝謝!現在,如果你不介意另一個noob-ish問題,我該如何爲用戶使用帶外鍵的user_id列? – rottendevice 2011-01-28 04:58:20

0

您希望在用戶模型和個人資料模型上使用has_one和belongs_to關聯。您的配置文件模型可能會有一個user_id列,並且將成爲「belongs_to」關係,而用戶將沒有該配置文件列,並且將成爲「has_one」關係。

然後在你的代碼,你可以這樣做:

profile = some_user.profile 

user = some_profile.user 
0

這聽起來像一個一對一的關聯。下面是你如何設置它:

class User < ActiveRecord::Base 
    has_one :profile 
end 

class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

Rails使這種關係非常簡單。 :)

確保配置文件表具有user_id列,以便此關聯將起作用。