Rails 模型和 ActiveRecord 中的子类化

发布于 2024-12-11 17:28:28 字数 307 浏览 0 评论 0原文

我正在编写一个电子商务类型的网络应用程序(不完全是,但给你一个想法)。我将展示不同类型的产品,这些产品彼此之间没有什么关系,但我希望有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神仙妹妹 2024-12-18 17:28:28

首先,继承意味着字段是继承的;因此,您不只是获取子类中父类的某些字段,而是获取父类的所有字段。

您可以通过多种方式实现您想要的目标:

  • 创建一个模块并将所有共享方法放入其中,并将其包含在每个模型中
  • 在子类中使用 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:

  • Create a module and place all your shared methods in it, and include it in each model
  • Use 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 your product table.
  • If your models share the same table, but are distinguished by, say, an attribute such as product_type you can use default_scope to always apply a condition such as default_scope where(:product_type => :hotel)

Use the API as a reference for the use of the aforementioned methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文