2012-03-31 92 views
3

我在我的應用程序兩種用戶類型相關的表和模型正確的命名約定:投資者顧問,它們都具有數據庫(投資模型一個獨立的模型和桌子,顧問模型,投資者表和顧問表)。什麼是在軌道3

我需要創建一個表來保持顧問的個人數據和不同的表,以保持投資者的個人資料(他們有輪廓完全不同的領域,所以我不能合併成一個單一的表)。我應該給它什麼名字?如果我將其稱爲investor_profile - 那麼每次我想從中獲取數據時,我都必須將其稱爲investor->investor_profile->field_name,但這對於鍵入投資者兩次似乎不太合適。

任何建議爲正確的名稱?或者,也許一個把戲,使其investor->profile->field_name

謝謝。

回答

2

你可以存儲investor_profilesadvisor_profiles不同的表有不同的模型InvestorProfile, AdvisorProfile(兩者可能從基Profile類繼承,假設他們有至少重疊一點點)。

但在你的模型關聯,使用:class_name選項隱藏_profiles

class Investor < ActiveRecord::Base 
has_one :profile, :class_name => "InvestorProfile" 
end 


class Advisor < ActiveRecord::Base 
has_one :profile, :class_name => "AdvisorProfile" 
end 

# And since the profiles probably overlap in some way 
# a profile base class which the other 2 profile classes extend 
class Profile < ActiveRecord::Base 
    # base options like name, address, etc... 
end 
class InvestorProfile < Profile 
    # Investor-specific stuff 
end 
class AdvisorProfile < Profile 
    # Advisor-specific stuff 
end 

在實踐中,然後,你可以稱其爲self.profile

# Use it as 
adv = Advisor.new 
puts adv.profile.inspect 

ActiveRecord::Associations documentation的說明的選項。

+0

+1給予從配置文件繼承的可能性... – Nobita 2012-03-31 21:03:30

+0

謝謝@邁克爾,非常好的答案,其他答案也很好,但你的信息最豐富。 – 2012-03-31 21:16:48

2

我認爲是有意義的有investor_profileadvisor_profile如果它們是不同的,因此,你不能使用相同的模型。

不用擔心訪問和重複的名字,因爲你可以這樣做:

class Investor 
    has_one :profile, class_name: "InvestorProfile" 
end 

並給予投資者的對象,你就可以做的東西一樣@investor.profile.profile_field

1

can name the association as you want並指定模型類的名稱:

class InvestorProfile < ActiveRecord::Base 
    # Investor_profiles table must contain an investor_id column 
    belongs_to :investor 
end 

class Investor < ActiveRecord::Base 
    # Thanks to the :class_name option rails know what a profile is 
    has_one :profile, :class_name => "InvestorProfile" 
end 

然後你可以使用像這樣的東西訪問配置文件字段@investor.profile.field_name