Reputation: 13548
Let's say you have two different categories of users with different profiles: one for music artists and one for listeners. The profiles for each have some overlapping attributes, and some different attributes. Should you have separate models for each different profile? Or should you just have a binary data column in the user table for whether the user is an artist or not? How would this be structured?
Upvotes: 3
Views: 1134
Reputation: 17020
You can use Single Table Inheritance
, which can be achieved by creating subclasses of a model.
Generate a Profile
model with a type:string
column (The name can be overriden):
$ rails g model Profile type:string
Now, in profile.rb
, subclass your model:
class Profile < ActiveRecord::Base
# Common profile attributes
end
class Artist < Profile
# Things specific to an artist profile
end
class Listener < Profile
# Things specific to a listener profile
end
When you create an Artist
or Listener
, it'll be saved in the profiles
table along with the type of the profile.
For example, if you do Artist.create
, it'll be saved in the profiles
table with type='Artist'
.
When you fetch the record, it will be returned in its appropriate model, be it Artist
, Listener
or a generic Profile
.
For more information about this technique, take a look at this question.
This blog post does a nice job explaining it as well.
Upvotes: 3
Reputation: 8240
One default called Profile containing the common attributes and two others (Artistic, Listener) models with the specific attributes of each one
And in the Profile, use a field to save the type (artistic or listener)
Just my opinian.
Upvotes: 0