Rails 引用另一个模型的 2 列

Rails reference 2 columns from another model

我已经看到了这个,但我不确定如何在我的特定情况下应用它 How do I add migration with multiple references to the same model in one table? Ruby/Rails

我正在尝试找到一种方法,让一个名为 ChildOrganization 的模型在 Rails 的一对多关系中引用另一个名为 Organization 的模型的 2 列4.2 网络应用。

例如,org1 和 org2 都列在组织模型中,并且有名称、地址等列...但在 ChildOrganization 模型中,应该列出 org1_id 和 org2_id在 'parent' 和 'child' 列下组成 parent\child 对。目标是拥有一个 ChildOrganization 模型,该模型列出 Organization 模型中的成对的两个。

ChildOrganization 有一个名为 organization_id 的引用列,它链接到组织 table 和另一个仅采用整数的列,名为 child_organization_id

在组织模型中(以下是错误的)

has_many :child_organizations, class_name: "ChildOrganization", foreign_key: "organization_id", dependent: :destroy
has_many :child_organizations, class_name: "ChildOrganization", foreign_key: "child_organization_id", dependent: :destroy

在 ChildOrganization 模型中

belongs_to :organization

更新

这是有效的方法。在 organization 模型中,我有以下内容。协会可以叫任何名字,它们不是models\tables的名字。您使用 class_name

指定模型
  # child_organization_parents/children associations map to foreign keys in the ChildOrganization table
  has_many :child_organization_parents, class_name: "ChildOrganization", foreign_key: "parent_org_id", dependent: :destroy
  has_many :child_organization_children, class_name: "ChildOrganization", foreign_key: "child_org_id", dependent: :destroy

ChildOrganization 模型中

  belongs_to :organization

迁移看起来像这样,我添加了一个空检查和一个索引

create_table :child_organizations do |t|
  t.integer :parent_org_id, null: false, index: true
  t.integer :child_org_id, null: false, index: true

  t.timestamps null: false
end

这是我用来创建将保存 2 个外键的模型的命令,记得在 运行 之前将 null:false 和 index:true 添加到迁移文件中。

rails g model ChildOrganization parent_org_id:integer child_org_id:integer --no-assets --no-test-framework

has_many 之后的第一个参数需要不同。

像这样:

has_many :child_organization_organizations, class_name: "ChildOrganization", foreign_key: "organization_id", dependent: :destroy
has_many :child_organization_child_organizations, class_name: "ChildOrganization", foreign_key: "child_organization_id", dependent: :destroy