I want to create a status
attribute for my Task
model 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?
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])
You should use the aasm gem. It has aasm_states for models, callback functionality etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With