2011-01-22 54 views
1

说我们有:如何比多态关联更好的方式分享轨道3与其他数据库模型的模型

class ProductProperties < ActiveRecord::Base 
belongs_to :sellable, :polymorphic => true, :dependent => :destroy 
end 

class Tee < ActiveRecord::Base 
has_one :product_properties, :as => :sellable, :autosave => true 
end 

class Pen < ActiveRecord::Base 
has_one :product_properties, :as => :sellable, :autosave => true 
end 

的,我们可以解决产品特性: @ Tee.productProperties.property或@ Pen.productProperties.property

有没有办法简单地访问@ Tee.property和@ Pen.property?

这将使它更简单,因为T恤和Pen每个人都有自己的属性(例如:@ Pen.ownProperty)

到目前为止,我的研究使我这个插件: https://github.com/brunofrank/class-table-inheritance。 有没有人使用过它,并使用它是一个好主意(我的直觉是,这将在每个新的rails版本中打破)?

谢谢!

回答

1

一种解决方法是定义一个方法,让您直接访问继承属性:

class Pen < ActiveRecord::Base 
    def some_property 
    product_properties.some_property 
    end 
end 

# These calls are equivalent 
@pen.some_property 
@pen.product_properties.some_property 

如果你有很多的属性,你可能会想动态做到这一点:

class Pen < ActiveRecord::Base 
    [ :property1, :property2, :property3 ].each do |property| 
    define_method(:property) do 
     product_properties.some_property 
    end 
    end 
end 

但是,这听起来像是Single Table Inheritance的主要候选人。您可以创建您的孩子模型(PenTee等)从其继承的父模型(Product)。它们具有Product的所有属性以及它们自己的特定属性。

看看网上的散步教程。