I would advise you to use another model in this situation, something like OrderStatus:
class OrderStatus < ActiveRecord::Base
validates :internal_reference, presence: true, uniqueness: true
has_many :orders
def translated(locale = :en)
I18n.t("activerecord.attributes.order_status.#{self.internal_reference}", locale: locale, default: self.internal_reference)
end
class Order < ActiveRecord::Base
belongs_to :order_status
validates :order_status_id, presence: true
And the records will look like this:
OrderStatus.first
# => OrderStatus id: 1, internal_reference: canceled
Order.first
# => Order id: 3, order_status_id: 1 # etc.
In your views, it could be:
order.order_status.translated(I18n.locale)
# looks for activerecord.attributes.order_status.canceled
# if nothing found, returns the internal_reference, here it would return `'canceled'`
This configuration is better than just constants :
- You can create as many statuses as you want,
- You can translate them directly (using
internal_reference as key for I18n),
- The statuses can be tested either if they are in english, french or whatever (thanks to
internal_reference,
- You can create statuses directly in your app, without rebooting it,
- You can set an attribute, like
status_code and makes ranges (kind of like HTTP requests statuses) and group them (ex: if status_code > 100)
You can also add an boolean attribute cant_be_deleted to prevent from deleting Statuses used in the code.
You might think it is overkill to do so, but I guarantee that the day you will want to translate / add / remove / change your Statuses, it will be much easier with Models rather than Constants. Trust me, I worked for an Online shop, handling Carts, Orders and Products, I know how painful it is to change from constants to models, everywhere in your already existing code ;-)
enumattribute type that suits your purpose pretty well: robots.thoughtbot.com/…typeis reserved and should not be used (except for Single Table Inheritance cases). Ruby on Rails relies on thistypeattribute to find from which Class comes from the record from the DB.