Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extend a model with rails?

I want to have a general product model that has basic info like name, description, sku number etc. I also want to have another model that is a specific type of product that essentially extends the product model. For example: I'd like to have a clothing model that has additional columns like color, size, etc.

What is the best practice to implement this? I am thinking polymorphism or Single Table Inheritance. Maybe I am going down the wrong path??

like image 899
Jakcst Avatar asked Dec 07 '25 07:12

Jakcst


1 Answers

Single Table Inheritance (documentation) is a common approach. Another is to use modules for shared functionality.

Here is an example of using modules.

module Product
  def method_for_all_products
    # ...
  end
end

class Clothing < ActiveRecord::Base
  include Product

  def clothing_specific_method
    # ...
  end
end

class Furniture < ActiveRecord::Base
  include Product
end
like image 53
nicholaides Avatar answered Dec 10 '25 00:12

nicholaides