Last Updated: February 25, 2016
·
10.46K
· wzywno

Case statement for Rails Enum

How to use 'case' statement for rails enum value.

When you want to execute different methods basing on the value of enum you can use case when statement instead of writing several if else statements. Below simple example.

Model class

class Lookup < ActiveRecord::Base
  enum status: { :new, :in_progress, :completed }
end

Case when Statement

case lookup_instance[:state]
when Lookup.states[:new]
...
when Lookup.states[:in_progress]
...
when Lookup.states[:completed]
...
end

Reference:
ActiveRecord::Enum

1 Response
Add your response

Or:

case lookup.state.to_sym
when :new
...
when :in_progress
...
when :completed
...
end
over 1 year ago ·