Domanda

I am wondering how do I add additional properties to a many to many relationship. I have two models that share a many to many relationship, Company and Profession.

Many professionals could belong to a Company

So my Company model looks like below

class Company < ActiveRecord::Base
  has_and_belongs_to_many :professions
end

The same people in the same profession could belong to multiple companies as well so

class Profession < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

Now I need to associate an hourly rate which could be different for each of the companies for the same profession. I am not very sure where to introduce the hourly rate property? Even if I were to add that to the joining table, how do I access that rate using active record?

È stato utile?

Soluzione

This is a typical scenario where you select has_many through over habtm. As a rule, if you only need to associate two models, no other info needed to be stored in the association, use habtm. For most cases, you have to use has_many through. You case falls under this scenario.

You want to save the hourly rate in the table that associates a Profession and a Company. If you have existing data that you want to migrate, you may want to look at this post How to migrate has_and_belongs_to_many to has_many through?. If you can drop the joins table you use for the habtm association, just drop it and create a new table.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top