【问题标题】:Rails4 - Child model association depending on Parent model attributeRails4 - 子模型关联取决于父模型属性
【发布时间】:2015-02-24 08:59:24
【问题描述】:

我有一个具有职业属性的用户模型。 假设用户可以是footballertennisman 用户注册时选择职业,以后可以更改。

我的用户模型包含最常见的属性,例如姓名、地址、体重、联系信息。 我想将其他特定属性存储在专用模型中,例如 footballer_profile、tennissman_profiles

我不能使用多态性,因为单个模型结构的信息差异太大。

如何根据我的“User.occupation”属性向我的用户模型声明特定的 has_one 条件?

这是最好的方法吗? 谢谢你的帮助

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model has-one


    【解决方案1】:

    你可以写:

    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,但该属性必须是一个 integer 列。如果您不想使用 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
    

    【讨论】:

    • 非常感谢,这正是我的想法。然而,迈克坎贝尔的回答让我三思而后行。
    【解决方案2】:

    对我来说听起来像是多态性的一个案例。

    class User < ActiveRecord::Base
      belongs_to :occupational_profile, polymorphic: true
    end
    
    class FootballerProfile < ActiveRecord::Base
      has_one :user, as: :occupational_profile
    end
    

    这样您就可以简单地建立和关联他们选择的职业的个人资料。

    【讨论】:

    • 你读过这个问题吗?它说我不能使用多态性,因为对于单个模型结构来说信息太不同了。
    • 该评论毫无意义,因此我忽略了它。多态性允许完全不同的模型来描述额外的配置文件信息。
    • 听起来很有趣。在我的逻辑中,基本元素将是 User,因为它很常见,您将其颠倒过来。您将如何管理用户改变其职业的能力?我对存储在 SportProfile 中的 id 感到非常不安。关于在视图中显示结果为 FootballerProfile.user.firstname 的信息的相同问题。然而,你拓宽了我的视野:)
    • 你可以忽略“belongs_to”这个词周围的语义,这并不重要。更改职业只是替换用户职业档案的一种情况,如何将其融入应用程序逻辑取决于您。要在 FootballerProfile 视图中显示用户信息,您将完全按照您所说的 @footballer_profile.user...
    • 感谢您的回答。到目前为止,访问者会转到注册页面并在此处找到一个表格,该表格将允许他填写所有信息 - 一般(用户)+特定(运动资料)。使用嵌套表单 + js(显示隐藏字段)和 form_for(@user)很容易。使用多态,每种运动的 form_for 都会有所不同,这是我们还不知道的。多态性需要一个专门的表格,有两个步骤:1 - 选择你的职业 2 - 填写 form_for(@sport_profile) 中的信息,调用一个 sportprofile#new 操作。我认为这不是最好的情况。不过还是很有趣。
    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多