2015-02-24 149 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

相关问题