postgresql 如何为具有两个外键的模型编写关联?

l7wslrjt  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(131)

我又回到了一个我自己还没有解决的问题上,我有一个shipments表,其中有两列addresses,即to_address_idfrom_address_id
在看了一个相关的问题(Same Model for Two belongs_to Associations migration)后,我仍然很困惑。这是我到目前为止的工作。我还没有运行迁移。我试图在我的脑海中解决这个问题,然后再为此而工作,浪费一两个小时。我真的很感谢你的帮助。

class AddAddressFromAndAddressToToAddress < ActiveRecord::Migration[6.0]
  def change
    add_reference :address, :address_from, null: false
    add_reference :address, :address_to, null: false
    add_foreign_key :address, :shipments, column: :to_address_id
    add_foreign_key :address, :shipments, column: :from_address_id
  end
en

字符串

cetgtptt

cetgtptt1#

如果我理解正确的话,你要添加原产地和目的地地址航运,正确吗?
在这种情况下:
如果要创建迁移以创建关系,

class AddOriginAndDestinyAddressToShipment < ActiveRecord::Migration[6.0]
  def change
    add_reference :shipments, :from_address, foreign_key: { to_table: :addresses }
    add_reference :shipments, :to_address, foreign_key: { to_table: :addresses }
  end
end

字符串
如果你想创建一个模型,

class CreateShipments < ActiveRecord::Migration[6.0]
  def change
    create_table :shipments do |t|
      t.datetime :deadline
      t.references :from_address, null: false, foreign_key: { to_table: :addresses }
      t.references :to_address, null: false, foreign_key: { to_table: :addresses }
      t.timestamps
    end
  end
end


发货模式应该是这样的

class Shipment < ApplicationRecord
  belongs_to :to_address, class_name: 'Address'
  belongs_to :from_address, class_name: 'Address'
end

kqqjbcuj

kqqjbcuj2#

我不需要迁移,因为外键已经就位了。我尝试的那个不工作,strong_migrations gem也在抱怨。我只需要把它连接好。
我想展示一下我是如何避免混淆的,所以我可以输入shipment.to_addressshipment.address_to,得到相同的结果。谢谢。

class Shipment < ApplicationRecord
  belongs_to :address_from, class_name: 'Address', foreign_key: :from_address_id
  belongs_to :from_address, class_name: 'Address', foreign_key: :from_address_id
  belongs_to :address_to,   class_name: 'Address', foreign_key: :to_address_id
  belongs_to :to_address,   class_name: 'Address', foreign_key: :to_address_id
end

class Address < ApplicationRecord
  has_many :shipments
end

字符串

相关问题