Silvertail
Silvertail

Reputation: 169

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:

    User----has_many----->Skill(smart)<---has_many----job_posting
                              ^
                              |
                           has_many
                              |
                          Application

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: myUser.skills.add(Skill.find(1)) myCompany.skills.add(Skill.find(1))...

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

P.P.S I'm using mysql as my database

Upvotes: 0

Views: 256

Answers (1)

geoandri
geoandri

Reputation: 2428

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
end

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

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

Upvotes: 1

Related Questions