sadaf2605
sadaf2605

Reputation: 7550

Class inheritance in rails active record

I have a Product table, which has multiple fields like product price, product manufacturer and so on which is common in every item. So I have made a belongs_to relationship with productItem. Every product item has its own specifications. Now I feel the necessity to make few common methods. From the concept of OOP, I have tried to make Parent class Sub class model, where subclass will inherit all the methods of parent. So I have tried doing following:

class Product < ActiveRecord::Base
  def check
    ...
  end
end

class ProductItem < Product
  belongs_to :product
end

which raises following error:

undefined method `some_field_id' for #<ProductItem:0x007f8cac666850>

So how can I do parent subclass model in rails?

Upvotes: 1

Views: 933

Answers (1)

Francesco Belladonna
Francesco Belladonna

Reputation: 11729

Class inheritance it's not for code sharing, you should rely on mixins for such a thing. Create a module like this, you can put it in app/shared/yourmodule.rb:

module Yourmodule

  def dosomething
  end

end

class Product
  include Yourmodule
end

class ProductItem
  include Yourmodule
end

Product.new.dosomething
ProductItem.new.dosomething

You can share attributes through STI though, but STI is recommended only if you share all parent attributes plus a few additional fields, be careful with it.

STI is simple: add (if you don't have it already) a type column to the table you want to inherit from, make it a string and don't set any default and leave it nullable. Now you can just do:

class Product < ActiveRecord::Base
end

class ProductItem < Product
end

You'll be able to access anything from Product

Upvotes: 2

Related Questions