我有两个Rails模型,Hub
和Advisor
。 Hub
的has_many Advisor
像这样:
class Hub < ApplicationRecord
has_many :advisors
end
我想将一个特定的Advisor
设置为该中心的经理。我已经在集线器中添加了manager_id
,如下所示:
class AddManagerToHub < ActiveRecord::Migration[5.1]
def change
change_table :hubs do |t|
t.references :manager, references: :advisors
end
end
end
但是我无法找出在模型中设置此关系的正确方法。逻辑要求应该是:
has_one :manager, class_name: 'Advisor', primary_key: :manager_id
但是当我这样保存时:
hub.manager = advisor
hub.save
未设置集线器ID。有什么作用?
Hubs表的表结构为:
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)
答案 0 :(得分:1)
由于在集线器中添加了manager_id
并引用了Advisor
,因此关联应如下所示:-
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
查询将类似于:-
hub.hub_manager = advisor
hub.save