试图实现双向自引用关联

时间:2016-12-01 17:16:16

标签: ruby-on-rails ruby

(我正在翻译代码,所以我为任何错误道歉!)

我正在尝试实现涉及Associates表和连接表Property的双向自引用关系。我试过跟this post但是仍然有问题。

它的工作方式是,associate可以是零或更多associates的所有者,因此associate可能有零或更多proprietors(在应用程序的上下文中更有意义)。

所以我创建了Property模型:

class CreateProperties < ActiveRecord::Migration
  def change
    create_table :properties do |t|
      t.integer :proprietor_id
      t.integer :property_id

      t.timestamps null: false
    end
  end
end

因此,每个条目的表格仅包含一个proprietor和一个property的ID。

按照上面链接的教程,我来到了这个配置:

associate

Associate.rb

... has_many :properties has_many :related_properties, :through => :properties has_many :proprietors, :class_name => "Property", :foreign_key => "proprietor_id" has_many :related_proprietors :through => :proprietors, :source => :associate ...

Property.rb

但是,当我尝试使用这些关系(belongs_to :associate belongs_to :related_properties, :class_name => "Associate" )时,我收到此错误:

<% @associate.related_properties.each do |property| %>

基本上,生成的SQL中的列名是错误的:PG::UndefinedColumn: ERROR: column properties.related_properties_id does not exist LINE 1: ... INNER JOIN "propriedades" ON "associados"."id" = "proprieda... ^ : SELECT "associates".* FROM "associates" INNER JOIN "properties" ON "associates"."id" = "properties"."related_properties_id" WHERE "properties"."associate_id" = $1 应该是properties.related_properties_id,而properties.proprietor_id也应该是properties.associate_id

我做错了什么,如何修复此代码以获得正确的关系?

1 个答案:

答案 0 :(得分:1)

您需要设置两个单独的关联,因为Property上的外键取决于Associates角色的内容。

class Associate
  # defines relations where Associate is the "owning" party
  has_many :properties_as_proprietor, 
    class_name: 'Property',
    foreign_key: 'proprietor_id'
  has_many :properties, 
    through: :properties_as_property,
    source: :property # what to select on Property

  # defines relations where Associate is the "owned" party
  has_many :properties_as_property, 
    class_name: 'Property',
    foreign_key: 'property_id'
  has_many :proprietors, 
    through: :properties_as_proprietor,
    source: :proprietor # what to select on Property
end

class Property
  belongs_to :proprietor, class_name: 'Associate'
  belongs_to :property, class_name: 'Associate'
end