Mene
Mene

Reputation: 354

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.

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

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 ?

And is it the best way to go ? Thank you for your help

Upvotes: 0

Views: 220

Answers (2)

Mike Campbell
Mike Campbell

Reputation: 7978

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.

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118271

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. Just remember, while you will be declaring, an attribute as enum, that attribute must be an integer column. If you don't want to go with enum, use a constant.

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

Upvotes: 2

Related Questions