omair azam
omair azam

Reputation: 580

Active Record Rails Inheritance - Auto Type casting based on type

My scenario


-> User has many machines

-> Machines can have 5 types

-> each machine type has its own processing mechanism.

-> I want to use type column to see which class this row belongs to. (Rails inheritance approach) as explained in this link Link.


My Question


-> access a machine from database e.g machine = Machine.first

-> then call machine.process (this process method should be called based upon the type of this machine). (I am expecting some type casting stuff here.)

Note: Each machine type has its process implementation which is different from other and it implemented in its own class.

I want to know best approach to implement this. Any help is appreciated.

Upvotes: 0

Views: 312

Answers (2)

omair azam
omair azam

Reputation: 580

After googling for some time I could figure out a gem that gave me exactly what I wanted.

active_record-acts_as Gem.

Other links that I found useful were:

Link1

Link2

Link3

Upvotes: 0

Daniil Maksimov
Daniil Maksimov

Reputation: 139

You can implement parent class Machine with common logic and children classes with personal logic.

rails g model machine type:string customer_id:integer
mkdir app/models/machines
touch app/models/machines/bmw.rb
touch app/models/machines/renault.rb
...

app/models/machine.rb

class Machine < ActiveRecord::Base
  belongs_to :customer
  ...
  def country
    raise NotImplementedError
  end
end

app/models/machines/bmw.rb

class Bmw < Machine
  ...
  def country
    :germany
  end
end

app/models/machines/opel.rb

class Renault < Machine
  ...
  def country
    :france
  end
end

For example:

  • First bmw Bmw.first
  • First any car Machine.first
  • Get customer first Renault Renault.first.customer
  • Country any car Machine.all.sample.country, this method will call from any the child class.

Upvotes: 1

Related Questions