簡體   English   中英

多態關聯或belongs_to關聯

[英]Polymorphic associations or belongs_to associations

在這種情況下,我正在使用多態關聯:

class Adress < ActiveRecord::Base
  belongs_to :addressable, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :addresses, as: :addressable
end

我現在想要的是一個用戶有一個家庭住址和一個工作地址。 我本可以有:

class User < ActiveRecord::Base
  has_one :home_address, as: :addressable
  has_one :work_address, as: :addressable
end

但是,我不知道哪個是家庭住址,哪個是工作地址​​。

我該如何實現?

你有一個Addresses表,保持一個字段為“ addressable_type在” Addresses表。 比您將能夠識別不同的地址。

您可以在地址表中包含這些字段,

t.integer :addressable_id
t.string  :addressable_type

或簡化版本:

t.references :addressable, polymorphic: true

謝謝

您可以設置STI。 您需要在地址模型中創建一個type列。

class Adress < ActiveRecord::Base

end

class WorkAddress < Address
   belongs_to :user
end

class HomeAddress < Address
   belongs_to :user
end

class User < ActiveRecord::Base
  has_one :work_address
  has_one :home_address
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM