Reputation: 580
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
Reputation: 580
After googling for some time I could figure out a gem that gave me exactly what I wanted.
Other links that I found useful were:
Upvotes: 0
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:
Bmw.first
Machine.first
Renault.first.customer
Machine.all.sample.country
, this method will call from any the child class.Upvotes: 1