Search code examples
ruby-on-railsactiverecordassociationsbelongs-to

Is there a way to specify an association_foreign_key for a belongs_to relation?


I have a model that uses a belongs_to relation. I want to be able to specify both the foreign_key and association_foreign_key values. However, I can only specify the foreign_key value for a belongs_to relation (http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference) Is there a way to solve this problem?

Here is my example:

I have a Client model. Its location_id key has to belong to the Region model, where ids are referred to by place_id. What I'd like to do is:

class ClientId < ActiveRecord::Base
  belongs_to :region, foreign_key: 'location_id', association_foreign_key: 'place_id'

However, I cannot specify the association_foreign_key here...


Solution

  • The association doesn't need to be declared both ways in the same model. You have to declare: has_one/many in the other related model.

    class Client < ActiveRecord::Base
      belongs_to :region, foreign_key: 'location_id'
    
    class Region < ActiveRecord::Base
      has_many :clients, foreign_key: 'place_id'