基于公共领域的Rails关系

时间:2014-09-01 07:42:16

标签: ruby-on-rails activerecord

我在ActiveRecord has_many关系中找到了不少主题,但我还没找到我想要的内容。

我有两个表,每个表都有xyz_id列。此ID是我订阅的API服务中的相应ID。

我希望在每个表的相应列中通过这些相应的ID建立has_many关系。这样,如果table_1中的项目的xyz_id为“abcdefg”,我可以执行table_1.relation之类的操作,它将返回table_2中匹配xyz_id的所有元素。我可以在我的代码中使用ActiveRecord并利用查询,但我认为必须有更好的方法。有什么想法吗?

编辑:我一句话。

1 个答案:

答案 0 :(得分:1)

ActiveRecord允许您在定义关系时指定任意fkeys,如下所示:

class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts, 
                          foreign_key: :xyz_id 
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies,
                          foreign_key: :xyz_id
end

来源:http://guides.rubyonrails.org/association_basics.html

相关问题