Search code examples
ruby-on-railsrelationshipsdatabase-relations

Database organization for separating two different types of the same model


So I want my User model to have_many Skills. I want there to be two different categories for the skills: a wanted skill, and a possessed skill.

For example, a user can add a skill to their profile that they possess, such as HTML. They can also add a skill to their profile that they wish to learn, such as Ruby on Rails. On their profile it'll list their current skills and wanted ones, separately.

From a high level, what's the best way to architect this? I just want there to be 1 Skill model with no duplicates, but I want there to be a way for users to have the 2 separate groups of skills in the database.


Solution

  • You can use single table inheritance

    class Skill < ActiveRecord::Base
    end
    
    class WantedSkill < Skill
       belongs_to :user
    end
    
    class PossessesSkill < Skill
      belongs_to :user
    end
    

    Your skills table should have a column called type where the type of the skill will be stored.

    WantedSkill.create(:name => "html")
    

    Above will save the record in the skills table with type 'WantedSkill'. You can retrieve it by

    WantedSkill.where(:name => "html").first
    

    your user associations can be like

    class User < ActiveRecord::Base
       has_many :wanted_skills
       has_many :possessed_skills
    end
    

    You can read documentation here