Ruby on rails Rails在非主键上添加外键

Ruby on rails Rails在非主键上添加外键,ruby-on-rails,activerecord,activemodel,Ruby On Rails,Activerecord,Activemodel,在Rails 5.1中,我有以下关系: class RootArea < ApplicationRecord has_many :common_areas end class CommonArea < ApplicationRecord belongs_to :root_area, foreign_key: 'area_id', optional: true end 我的目标是将公共区域连接到区域id上的根区域-,而不仅仅是id,以便单个根区域条目可以“具有”多个公共区域

在Rails 5.1中,我有以下关系:

class RootArea < ApplicationRecord
  has_many :common_areas
end

class CommonArea < ApplicationRecord
  belongs_to :root_area, foreign_key: 'area_id', optional: true
end
我的目标是将
公共区域
连接到
区域id
上的
根区域
-,而不仅仅是
id
,以便单个根区域条目可以“具有”多个公共区域

例如,美国(
RootArea
)有加利福尼亚州(
CommonArea
),德克萨斯州(
CommonArea
)等

我尝试使用迁移和外键执行此操作,如下所示:

add_foreign_key :common_areas, :root_areas, primary_key: :area_id
虽然起初这似乎效果不错,但最终还是失败了:

>>> RootArea.create!(area_id: 1111, 
                     localname: ’test', 
                     globalname: ’test') # OK

>>> CommonArea.create!(area_id: 9999, 
                       localname: ’test', 
                       globalname: ’test') # OK

>>> RootArea.first.common_areas << CommonArea.first # Error

=> # SQL (44.3ms)  UPDATE "common_areas" SET "root_area_id" = $1, "updated_at" = $2 WHERE "common_areas"."id" = $3  [["root_area_id", 19], ["updated_at", "2018-02-20 14:45:52.545450"], ["id", 1]]
>>RootArea.create!(地区识别号:1111,
localname:'test',
全局名称:“测试”)#好的
>>>公共区域。创建!(地区识别号:9999,
localname:'test',
全局名称:“测试”)#好的
>>>RootArea.first.common_area#SQL(44.3ms)更新“common_area”设置“root_area_id”=$1,“updated_at”=$2,其中“common_area”。“id”=$3[“root_area_id”,19],“updated_at”,“2018-02-20 14:45:52.545450”,[“id”,1]]
输出提示Rails尝试将
CommonArea
的属性
root\u-id
设置为
RootArea
的主键(
id
而不是
area-id


例如,在上面的示例中,生成的sql语句应该将
root\u area\u id
设置为
1111
,而不是
19

,今天晚上晚些时候,我从Rails IRC频道寻求了一些进一步的帮助,最终用户
dionysus69
向我指出了这一点,这与我正在寻找的内容非常相似对于供将来参考,这是最终解决方案:

class RootArea < ApplicationRecord
  has_many :common_areas, foreign_key: 'root_area_id', primary_key: 'area_id'
end

class CommonArea < ApplicationRecord
  belongs_to :root_area, foreign_key: 'root_area_id', primary_key: 'area_id', optional: true
end
类根区域
现在我可以成功了

>>  RootArea.first.common_areas << CommonArea.first

>RootArea.first.common_area您能否分享您的类和关系?已更新。rwolddThanks。你没有叫“区域”的课吗?看来使用
可以更轻松地实现您想要的功能,因为它有很多。。。通过
我不太明白为什么既有
根区域
又有
公共区域
表。或者为什么这不是一个HMT等等。所以,我试着做以下几件事:例如,加利福尼亚州
属于美国,德克萨斯州
属于美国等等。但我也需要能够在美国、普通地区和加利福尼亚州、得克萨斯州等地工作。这样做的最佳方式是什么?
>>  RootArea.first.common_areas << CommonArea.first