How to share a model with other database models in rails 3 in a better way than Polymorphic Associations
Say we have:
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
The we can address the product properties as: @Tee.productProperties.property or @Pen.productProperties.property
Is there a way to have access to simply @Tee.property and @Pen.property?
This would make it much simpler since Tee and Pen each have their own attributes (ex: @Pen.ownProperty)
So far my research lead me to this plugin: https://github.com/brunofrank/class-table-inheritance. Has anyone used this, and is using it a go开发者_开发问答od idea (my gut feeling is that this will break at every new rails release)?
Thanks!
One workaround would be to define a method to give you direct access to the inherited properties:
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
If you have a lot of properties, you'll probably want to do this dynamically:
class Pen < ActiveRecord::Base
[ :property1, :property2, :property3 ].each do |property|
define_method(:property) do
product_properties.some_property
end
end
end
However, this sounds like a prime candidate for Single Table Inheritance. You create a parent model (Product
) that your child models (Pen
, Tee
etc) inherit from. They have all the properties of Product
, as well as their own specific properties.
Have a look online for a walk through tutorial.
精彩评论