I have 3 models: Company, Portable and Jobsite. I want to be able to call company.portables, company.jobsites, portable.company, portable.jobsite, jobsite.portables and jobsite.company. I've setup my associations like this:
class Company
has_many :portables
has_many :jobsites, through: :portables
end
class Portable
belongs_to :company
belongs_to :jobsite
end
class Jobsite
has_many :portables
has_one :company, through: :portables
end
I can call everything successfully except jobsite.company. When I make this call, I get:
ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'Jobsite#company' where the :through association 'Jobsite#portables' is a collection. Specify a has_one or belongs_to association in the :through option instead.
What is the proper way to setup these associations? Do I have to make the jobsite to company association a belongs_to :company on the jobsite and add the jobsite_id to the company? It seems there should be another way to achieve this with what I have already setup.
If you think about it, the schema as described just can't work. If you really want Jobsite to have only one Company, then it can't go through Portable, bevause Jobsite has many Portables.
So your left with two choices: - If what you mean is one Jobsite should have a 'main' company, then have a Jobsite
has_one :companydirectly, without the:throughpart. - If what you mean is thay Jobsites can really have many Companies through their many Portables, then just change your code tohave_many:.Bonus choice, you can also get fancy with the options here by doing something like:
You can do all kinds of fancy stuff that way.