I've been researching this for a few days now, and I know there is an abundance of articles that talk about single table inheritance and polymorphic associations with Rails. A lot of helpful material is from 2009 or before and I'm wondering if there is a better approach to this problem now.
The application has a couple of different user types (ie, Buyer and Seller), each of which have a profile. The profile for each user type is really different, so I'm currently ruling out the idea of one generic "profile" table.
which is the same as this solution.
class User < ActiveRecord::Base
# authentication stuff
end
class UserType1 < User
has_one :user_type_1_profile
end
class UserType2 < User
has_one :user_type_2_profile
end
...
class UserTypeN < User
has_one :user_type_n_profile
end
Based on my research, this is kind of a "mixed model" design.
Honestly, at this point I don't know of any other solution that would work. Every time I've seen similar questions asked I see the idea of polymorphic associations brought up. Could someone elaborate how a polymorphic association would work in this case?
Does anyone have any other design suggestions?
You would be better off with a polymorphic association here with various profile types.
class User < ActiveRecord::Base
belongs_to :profile, :polymorphic => true
end
class ProfileTypeA < ActiveRecord::Base
has_one :user, :as => :profile
end
class ProfileTypeB < ActiveRecord::Base
has_one :user, :as => :profile
end
Which would require you have a migration/table like this:
change_table :users do |t|
t.integer :profile_id
t.string :profile_type
# OR (same thing, the above is more explicit)
t.references :profile, :polymorphic => true
end
There's more info on this in the Guide: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With