rails - belongs_to任何不同的型号

时间:2014-06-04 20:21:07

标签: ruby-on-rails

我的数据库中有一些模型:

- customer
    has_many documents
- charts
    has_many documents
- pages
    has_many documents

上述任何型号都可以包含多个文档

如何在文档模型中执行此操作?是否有任何关系可以接受不同的模型?

1 个答案:

答案 0 :(得分:3)

是的,有可能。这个概念叫做多态关联,可以使用Ruby on Rails这样做:

class Document < ActiveRecord::Base
  belongs_to :owner, polymorphic: true

class Customer < ActiveRecord::Base
  has_many :documents, as: :owner

它使用2列工作:一列保存所有者的类型,第二列保存所有者的ID:

Document.create(owner_type: 'Customer', owner_id: customer.id)

然后,您可以在文档对象上调用方法.owner

doc = Document.first
doc.owner # => Can either return a Customer, Chart or Page record

您可能希望添加一些安全性,以防止为不应该具有此关系的所有者创建文档:

class Document < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
  validates :owner_type, inclusion: { in: %w( Customer Chart Page ) }

这将阻止创建这样的文档:

Document.create(owner_type: 'kittyCat', owner_id: 77) # won't work