【问题标题】:How do I model these relationships?我如何为这些关系建模?
【发布时间】:2010-10-26 03:25:40
【问题描述】:

我有一个联系人模型,其中包括姓名、地址、电话号码等。

我有一个用户模型,应该有一个联系人。

我有一个拥有多个联系人的客户模型。

我有一个有很多联系人的 Producer 模型。

联系人只能是用户、用户和客户、用户和生产者,或者这三者的任意组合。当一个联系人链接到多个模型以保证数据完整性时,我还需要确保链接相同的联系人记录。

我应该如何创建关联?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3


    【解决方案1】:

    这对于polymorphic association 来说似乎是一个不错的应用程序:

    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
    

    这为三个关联中的每一个提供了一个连接表。通过向联接表中添加行,每个联系人可以不属于任何一个、一个或多个其他三个模型。

    【讨论】:

    • 但是联系人如何同时属于用户、客户和生产者。这样不会联系只与单一类型相关联吗?
    猜你喜欢
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    相关资源
    最近更新 更多