In Rails, how should I implement a Status field for a Tasks app – integer or enum?

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:

<td><%= task.status_name %></td>

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 ','}"

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)