Reputation: 354
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
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
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