Pezholio
Pezholio

Reputation: 2694

Defining has_one with different foreign key

I have two Rails models, Hub and Advisor. A Hub has_many Advisors like so:

class Hub < ApplicationRecord
  has_many :advisors
end

And I'd like to set one particular Advisor to be the manager of that hub. I've added a manager_id to the hubs like so:

class AddManagerToHub < ActiveRecord::Migration[5.1]
  def change
    change_table :hubs do |t|
      t.references :manager, references: :advisors
    end
  end
end

But I can't figure out the correct incantation to set this relation in the model. Logic would dictate that it should be:

has_one :manager, class_name: 'Advisor', primary_key: :manager_id

But when I save like so:

hub.manager = advisor
hub.save

The hub ID doesn't get set. What gives?

The table structure of the Hubs table is:

Column      |        Type         | Collation | Nullable |             Default              | Storage  | Stats target | Description 
------------------+---------------------+-----------+----------+----------------------------------+----------+--------------+-------------
id               | bigint              |           | not null | nextval('hubs_id_seq'::regclass) | plain    |              | 
name             | character varying   |           |          |                                  | extended |              | 
address_line_1   | character varying   |           |          |                                  | extended |              | 
address_line_2   | character varying   |           |          |                                  | extended |              | 
postcode         | character varying   |           |          |                                  | extended |              | 
longitude        | double precision    |           |          |                                  | plain    |              | 
latitude         | double precision    |           |          |                                  | plain    |              | 
ward_mapit_codes | character varying[] |           |          | '{}'::character varying[]        | extended |              | 
manager_id       | bigint              |           |          |                                  | plain    |              | 
Indexes:
"hubs_pkey" PRIMARY KEY, btree (id)
"index_hubs_on_manager_id" btree (manager_id)
Referenced by:
TABLE "advisors" CONSTRAINT "fk_rails_d86df62174" FOREIGN KEY (hub_id) REFERENCES hubs(id)

Upvotes: 0

Views: 50

Answers (1)

Anand
Anand

Reputation: 6531

Since manager_id is added in hub which reference to Advisor so Association should be like this: -

class Hub < ApplicationRecord
  has_many :advisors
  belongs_to  :hub_manager, class_name => "Advisor", :foreign_key => "manager_id", optional: true
end

class Advisor < ApplicationRecord
  belongs_to :hub
  has_many :owned_hubs, class_name => "Hub", :foreign_key => "manager_id",
end

Query will be like as: -

hub.hub_manager = advisor
hub.save

Upvotes: 1

Related Questions