agente_secreto
agente_secreto

Reputation: 8079

Subclassing in Rails models and ActiveRecord

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?

Upvotes: 2

Views: 2172

Answers (1)

Roland Mai
Roland Mai

Reputation: 31097

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.

Upvotes: 6

Related Questions