Вопрос

I have a has_one association for a location on a company entity:

class Location < ActiveRecord::Base
  attr_accessible :city, :country, :postal_code, :state
end

class Company < ActiveRecord::Base
  has_one :headquarters, :class_name => "Location"
end

The underlying schema for the company entity contains a location_id attribute. I expect I should be able to access a company's headquarters location info like so:

Company.find(12345).headquarters

However, this results in an exception:

SELECT "locations".* FROM "locations" WHERE "locations"."company_id" = 12345 LIMIT 1
ActiveRecord::StatementInvalid: PGError: ERROR:  column locations.company_id does not exist

I am confused as to why this is behaving this way. I expect the FK to be in companies, not locations (i.e. SELECT * FROM location WHERE locations.id = 12345). I have other lookups defined this same way and they behave as I expect.

A few things to note:

  • A location does not belong to a company, many entity types can have a location
  • I have tried being more/less verbose in my association definition, seems to make no difference
  • I also at one point tried 'has_one :location' to keep things simple, same result

Any help is appreciated.

:)

Это было полезно?

Решение

It sounds like you should be using belongs_to rather than has_one. Specifically,

class Company < ActiveRecord::Base
  belongs_to :headquarters, :class_name => "Location", :foreign_key => "location_id"
end

because you're saying that the foreign key is on the Company rather than the Location.

Другие советы

When you say, a Company has_one location, you imply that it's upto the Locations table to have the FK. A has_one relationship is a one-to-one relationship and in your case it makes perfect sense to add a company_id to the Locations table.

A belongs_to relationship (i.e. Location belongs_to Company) won't make sense here, because that will allow you to link multiple companies to one location. Unless, of course, you want to allow that, lose the has_one relationship on the Company model and add a belongs_to relationship on the Location model instead.

Update

company has_many_and_belongs_to location would be a better choice of relationship, given that a company can have many locations and one location can have many companies.

I would just add an extra column in the locations table (is_headquarter) to identify a company's headquarter.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top