2015-02-24 134 views
0

我有一個擁有職業屬性的用戶模型。 假設用戶可以是footballertennisman 當用戶註冊時,他選擇職業,並可以稍後更改。Rails4 - 根據父模型屬性的子模型關聯

我的用戶模型包含最常見的屬性,如姓名,地址,重量,聯繫信息。 我想在專用模型中存儲其他特定屬性,例如footballer_profile,tennissman_profiles

我不能使用多態性,因爲單個模型結構的信息太不同了。

如何根據我的「User.occupation」屬性向我的用戶模型聲明特定的has_one條件?

這是最好的方式嗎? 感謝您的幫助

回答

2

你可以寫:

class User < ActiveRecord::Base 

    enum occupation: [ :footballer, :tennissman ] 

    self.occupations.each do |type| 
    has_one type, -> { where occupation: type }, class_name: "#{type.classify}_profile" 
    end 
    #.. 
end 

請仔細閱讀#enum瞭解它是如何工作的。只是記得,而你會聲明,屬性爲枚舉,那屬性必須是整數列。如果您不想使用enum,請使用常量。

class User < ActiveRecord::Base 

    Types = [ :footballer , :tennissman ] 

    Types.each do |type| 
    has_one type, -> { where occupation: type.to_s }, class_name: "#{type.classify}_profile" 
    end 
    #.. 
end 
+0

非常感謝,正是我所想到的。 然而,麥克坎貝爾的回答讓我想到了最好的選擇。 – Patient55 2015-02-24 10:41:11

1

聽起來像是一個多態對我來說。

class User < ActiveRecord::Base 
    belongs_to :occupational_profile, polymorphic: true 
end 

class FootballerProfile < ActiveRecord::Base 
    has_one :user, as: :occupational_profile 
end 

這樣,您可以簡單地構建並關聯他們所選職業的個人資料。

+0

你讀過這個問題了嗎?它說**我不能使用多態,因爲單個模型結構的信息太不同了。** – Pavan 2015-02-24 09:43:23

+1

該評論沒有意義,因此我忽略了它。多態性允許完全不同的模型來描述額外的配置文件信息。 – 2015-02-24 10:01:50

+0

聽起來很有趣。在我的邏輯中,基本元素將是用戶,因爲它很常見,您將其顛倒過來。 你將如何管理用戶變更職業的能力?我對存儲在SportProfile內的id感到很不安。 同樣的問題顯示在FootballerProfile.user.firstname結果的視圖中的信息。但是,你放寬了我的想法:) – Patient55 2015-02-24 10:39:01