Silvertail Silvertail - 1 year ago 50
Ruby Question

Several Rails many to many relationships

I'm creating an app that will have several many to many relationships. Here is one example: An app user will have several skills. At the same time, many job_posts will have several skills. I'd like to be able to reuse the skill models so I could have something like this:


So you see, I want to basically be able to create one skill (in this example: "smart"), and then reference that skill from several different models using has_many relationships.

What is the best way to do this? I'd like to avoid creating a bunch of extra models to handle the relationships since I have several of these setups in my app.

In the end, it would be nice to be able to do something like this:

I know there is no such thing as skills.add(). Please suggest what I could use instead if you have something constructive. Thanks :)

I'm using mysql as my database

Answer Source

I think that this is a typical example of polymorphic association.You can check the relevant documentation here at section 2.9. In your case you could use

class Skill < ActiveRecord::Base
  belongs_to :skillable, polymorphic: true

class User < ActiveRecord::Base
  has_many :skills, as: :skillable

class JobPosting< ActiveRecord::Base
  has_many :skills, as: :skillable