简体   繁体   English

Rails4-子模型关联取决于父模型属性

[英]Rails4 - Child model association depending on Parent model attribute

I have a User model that has an occupation attribute. 我有一个具有职业属性的用户模型。 Let's say a user can be a footballer or a tennisman When the user sign up, he selects the occupation, and can change it later. 假设某个用户可以是footballertennisman当用户注册后,他选择了职业,以后可以进行更改。

My User model contains the most common attributes, like name, address, weight, contact infos. 我的用户模型包含最常用的属性,例如名称,地址,重量,联系信息。 I want to store the other specific attributes in dedicated models, such as footballer_profile, tennissman_profiles 我想将其他特定属性存储在专用模型中,例如footballer_profile,tennissman_profiles

I can not use polymorphism since the infos are too different for a single model structure. 我不能使用多态性,因为单个模型结构的信息太不同了。

How can I declare to my User model a specific has_one condition depending on my "User.occupation" attribute ? 如何根据我的“ User.occupation”属性向用户模型声明特定的has_one条件?

And is it the best way to go ? 这是最好的方式吗? Thank you for your help 谢谢您的帮助

You can write : 你可以写 :

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

Please read #enum to understand how it works. 请阅读#enum以了解其工作原理。 Just remember , while you will be declaring, an attribute as enum , that attribute must be an integer column. 只需记住 ,当您将要声明的属性为enum时 ,该属性必须是整数列。 If you don't want to go with enum , use a constant. 如果您不想使用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

Sounds like a case for polymorphism to me. 听起来对我来说是多态的情况。

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

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

This way you can simply build and associate the profile for the occupation they've chosen. 这样,您可以简单地为他们选择的职业建立和关联个人资料。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM