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?
Let’s say you have two different categories of users with different profiles: one for
Share
You can use
Single Table Inheritance, which can be achieved by creating subclasses of a model.Generate a
Profilemodel with atype:stringcolumn (The name can be overriden):Now, in
profile.rb, subclass your model:When you create an
ArtistorListener, it’ll be saved in theprofilestable along with the type of the profile.For example, if you do
Artist.create, it’ll be saved in theprofilestable withtype='Artist'.When you fetch the record, it will be returned in its appropriate model, be it
Artist,Listeneror a genericProfile.For more information about this technique, take a look at this question.
This blog post does a nice job explaining it as well.