If I have a model scheme like this:
Company 1---* Customer 1---* Car 1---* Workcard
Or in Rails language:
class Company < ActiveRecord::Base has_many :customers end
class Customer < ActiveRecord::Base belongs_to :company has_many :cars end
class Car < ActiveRecord::Base belongs_to :customer has_many :workcards end
class Workcard < ActiveRecord::Base belongs_to :car end
I can easily extend the associations in Company with
class Company < ActiveRecord::Base has_many :customers has_manu :cars, :through => :customers end
But what if I also want a direct associations to Workcard? Like this?
class Company < ActiveRecord::Base has_many :customers has_manu :cars, :through => :customers has_manu :workcards, :through => :cars end
When I do this (assuming, that I've filled the DB with relevant data)
company = Company.find(1) company.customers => Works fine company.cars => Works fine
company.workcards => Gives the following error:
ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column 'cars.company_id' in 'where clause': SELECT workcards.* FROM workcards INNER JOIN cars ON workcards.car_id = cars.id WHERE ((cars.company_id = 1))
So ActiveRecord assumes, that the Car model should have a direct association to Company instead of going through the other "has_many through" association between Company and Cars.
How do I go around and implement this? Should I default to making a finder method
class Company < ActiveRecord::Base has_many :customers has_manu :cars, :through => :customers
def workcards # Loop through all cars, find related workcards, and return them merged ... end end
Or is there a better approach?
- Carsten