Friday, 31 July 2015

Rails 4 ENUM Feature

I know we all are aware about all the major upgrades with Rails 4, like concerns, decorator, presenter, strong parameter etc. and have started using them pretty well but there is an another really great feature introduced with Rails 4 ActiveRecord is ENUM module that we may not have given much attention to.

So let me introduce you with this power of Rails 4:

We often need an attribute in model where we want to save some kind of STATUS for that particular record, and this is where we can use this feature in our application.

Let me explain you the clear difference between the implementation in Rails 3 & Rails 4 with an example.
 

Rails 3 implementation :


class Order < ActiveRecord::Base
# schema change may look like this:
# add_column :orders, :status, :string
  
  STATUS = ["request", "processing", "shipping", "done"]
  
  scope :status, -> (status) { where status: status }
end

order = Order.last
order.update(status: Order::STATUS[0]) # => true

order.status # => "request"

Order.status("request") # => a scope to find all orders with "request" status

Rails 4 implementation :


class Order < ActiveRecord::Base
# schema change may look like this:
# add_column :orders, :status, :integer, default: 0 # defaults to the first value (i.e. "request")
  
  enum status: ["request", "processing", "shipping", "done"]
  
end

order = Order.last
order.update(status: "request") # => true

order.status # => "request"

order.request? # =>  check if status is "request"

order.request! # =>  update! the order with status set to "request"

Order.request # => a scope to find all orders with "request" status


Internally these states are mapped to integers in the database to save space. Also its worth mentioning here that methods added by enum saves us from writing scopes and methods to do above such operations.


There is a lot new features introduced with Rails 4 in developers benefit, this is one of them I though to share.

Happy Reading... :)

2 comments: