2

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?

1
  • what about single table inheritance? Commented Oct 26, 2011 at 12:23

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.