Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a status attribute for a model

I want to create a status attribute for my Taskmodel that would indicate where it is in a three part progress in this order: open => in-progress => complete. It would work in a way similar to how an Amazon package is delivered: ordered => shipped => delivered. I was wondering what would be the best way to setup this attribute. I may be wrong but creating three separate boolean attributes seemed sort've redundant. What's the best way to accomplish this?

like image 654
Carl Edwards Avatar asked Jun 21 '15 12:06

Carl Edwards


2 Answers

Rails 4 has an built in enum macro. It uses a single integer column and maps to a list of keys.

class Order
  enum status: [:ordered, :shipped, :delivered]
end

The maps the statuses as so: { ordered: 0, shipped: 1, delivered: 2}

It also creates scopes and "interrogation methods".

order.shipped?
Order.delivered.all

It will also map the enum values when writing queries with hash arguments:

Order.where(status: [:shipped, :delivered])
like image 84
max Avatar answered Oct 13 '22 23:10

max


You should use the aasm gem. It has aasm_states for models, callback functionality etc.

like image 1
nesiseka Avatar answered Oct 13 '22 22:10

nesiseka