Rails 4: has_many through association not working - tricky association key handling

445 Views Asked by At

UPDATED QUESTION:

NOTE: Org table in remote db (likely source of problem)

A has_may through association is not working and cannot figure out why. Hoping someone can identify the problem.

Company model (companies table in local db)

has_many :locations, class_name: "Org", primary_key: :name, foreign_key: :c_name
has_many :reviews, through: :locations

Org model (orgs table in remote db, using establish_connection to reach it)

belongs_to :company, primary_key: :name, foreign_key: :c_name
has_many :reviews, primary_key: :key, foreign_key: :location_id

Review model (reviews table in local db)

I would like to do:

company.reviews.count

But it fails as it is trying to reach orgs table on local db and, of course, can't find it. company.locations.count works just fine as expected tho.

2

There are 2 best solutions below

1
On

Try changing the org model's first belongs_to line to:

belongs_to :c_name, class_name: 'Company'
1
On

just change

has_many :reviews, through: :locations, class_name: "Org"

to

has_many :reviews, through: :locations

Or if model's class is not Review, then

has_many :reviews, through: :locations, class_name: "MyAwesomeReviewModelClass"