Rails 模型和 ActiveRecord 中的子类化
我正在编写一个电子商务类型的网络应用程序(不完全是,但给你一个想法)。我将展示不同类型的产品,这些产品彼此之间没有什么关系,但我希望有一个 Product 父类,以便对所有子类有一个共同的视图,并共享一些字段和行为。
但这给我带来了很多问题,特别是关于 ActiveModel:产品不应该有自己的表,但我希望其子类(酒店、餐厅等)中的某些字段从中继承这些字段。我该怎么办呢?
拥有 Product 父类的另一个原因是,最终我将需要使用 Product.all 和类对象的不同范围。
也许我完全被误导了,所以请随意建议任何方法来做到这一点。也许使用模块?
I am programming an e-commerce type web app (not exactly, but to give you an idea). I will be displaying different types of products that have little to do with one another, but I would like to have a Product parent class, to have a common view for all the subclasses, and share some fields and behaviours.
But this raises many questions to me, specially regarding to ActiveModel: Product shouldnt have its own table, but I would want some fields in its subclasses (hotel, restaurant, etc) to inherit those fields from it. How would I go about that?
Another reason to have a Product parent class would be that eventually I will need to use Product.all and different scopes of the class objects.
Maybe I am totally misguided, so feel free to suggest any way to do this. Maybe using a module?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,继承意味着字段是继承的;因此,您不只是获取子类中父类的某些字段,而是获取父类的所有字段。
您可以通过多种方式实现您想要的目标:
set_table_name
来路由模型以使用另一个表。如果您有多个表与product
表共享相同的字段,这非常有用。product_type
之类的属性来区分,您可以使用default_scope
始终应用诸如default_scope 其中的条件(:product_type => :hotel)
使用 API 作为上述使用的参考方法。
First, inheritance implies that fields are inherited; therefore, you don't just a get some fields you get all the fields for the parent class in the subclass.
You can achieve what you want in multiple ways:
set_table_name
in the subclass to route the model to use another table. This is useful if you have multiple tables that share the same fields as yourproduct
table.product_type
you can usedefault_scope
to always apply a condition such asdefault_scope where(:product_type => :hotel)
Use the API as a reference for the use of the aforementioned methods.