簡體   English   中英

如何建立這些關系的模型?

[英]How do I model these relationships?

我有一個聯系人模型,其中包括姓名,地址,電話號碼等。

我有一個應該有一個聯系人的用戶模型。

我有一個has_many聯系人的客戶模型。

我有一個具有很多聯系的生產者模型。

聯系人只能是用戶,用戶和客戶,用戶和生產者,或這三者的任意組合。 我還需要確保當一個聯系人鏈接到多個模型以確保數據完整性時,是否鏈接了相同的聯系人記錄。

我應該如何創建關聯?

這看起來是多態關聯的一個很好的應用程序:

class User < ActiveRecord::Base
  has_one :contact, :as => :contactable
end

class Customer < ActiveRecord::Base
  has_many :contacts, :as => :contactable
end

class Producer < ActiveRecord::Base
  has_many :contacts, :as => :contactable
end

class Contact < ActiveRecord::Base
  belongs_to :contactable, :polymorphic => true
end

編輯

似乎我並沒有完全閱讀規范:)要將同一聯系人與多個用戶,客戶等相關聯,可以使用has_many :through

class User < ActiveRecord::Base
  has_one :user_contact, :dependent => :destroy
  has_one :contact, :through => :user_contact
end

class Customer < ActiveRecord::Base
  has_many :customer_contacts, :dependent => :destroy
  has_many :contacts, :through => :customer_contacts
end

class Producer < ActiveRecord::Base
  has_many :producer_contacts, :dependent => :destroy
  has_many :contacts, :through => :producer_contacts
end

class UserContact
  belongs_to :user
  belongs_to :contact
end

class CustomerContact
  belongs_to :customer
  belongs_to :contact
end

class ProducerContact
  belongs_to :producer
  belongs_to :contact
end

class Contact < ActiveRecord::Base
  has_many :user_contacts, :dependent => :destroy # might use 'has_one' here depending on your requirements
  has_many :users, :through => :user_contacts
  has_many :customer_contacts, :dependent => :destroy
  has_many :customers, :through => :customer_contacts
  has_many :producer_contacts, :dependent => :destroy
  has_many :producers, :through => :producer_contacts
end

這為您提供了三個關聯中的每個關聯表。 通過將行添加到聯接表,每個Contact可以屬於三個模型中的任何一個,不屬於其中一個或不屬於其中三個。

暫無
暫無

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

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