Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different profile types

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?

like image 638
Justin Meltzer Avatar asked Dec 29 '25 03:12

Justin Meltzer


1 Answers

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.

like image 190
Matheus Moreira Avatar answered Dec 30 '25 15:12

Matheus Moreira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!