For a Rails 3.0 Todo app, I have a Tasks model with a Status field. What\'s the best way to store the Status field data (field type) and still display a human-r
1.It depends on how much you want to optimize queries on the DB.
2.Not really, it is not supported 'out of the box' by AR. # As of Rails 4 enums are supported out of the box.
3.IMHO you can use strings without a big performance penalty (just remember to add field to an index). I would do this because it's easier to internationalize and to maintain. However, you can go with integers if you need extra performance.
You may take a look on 2 SO threads here and here where this is debated.
4.If you want to keep them as integer, here is how you can accomplish this:
class Task << AR::Base
NORMAL = 1
ACTIVE = 2
COMPLETED = 3
STATUSES = {
NORMAL => 'normal',
ACTIVE => 'active',
COMPLETED => 'completed'
}
validates_inclusion_of :status, :in => STATUSES.keys,
:message => "{{value}} must be in #{STATUSES.values.join ','}"
# just a helper method for the view
def status_name
STATUSES[status]
end
end
and in view:
<%= task.status_name %>
If you want to use strings, it's more simplified:
STATUSES = ['normal', 'active', 'completed']
validates_inclusion_of :status, :in => STATUSES,
:message => "{{value}} must be in #{STATUSES.join ','}"