views:

26

answers:

2

I need some help with this, please ...

If I save a transaction status as a code in the db, but I want to translate them to meaningful names how do I do that? Is that even recommended? If no, what would be an alternative to that?

For example: in the db the statuses are "S", "P", "A" and in the actual application I'd like to display: "Submitted", "Pending", "Approved" accordingly.

Thank you!

+1  A: 

Say for example you have a model called Account in which you are storing the transaction status in a column called status whose value will be ione of the codes that you have mentioned, you can do

class Account < ActiveRecord::Base
  TRANSACTION_STATUS = {
    "S" => "Submitted",
    "P" => "Pending",
    "A" => "Approved"
  }

  def status
    TRANSACTION_STATUS[self[:status]]
  end
end

By this way, your are overriding the method status provided by activerecord on Account object.

Depending on how you are going to use the status field, you might be required to create proper index on those columns (for ex: if you are going to select accounts with pending transaction, etc)

Selva
Sweet! That worked out perfectly! Thanks a lot!
Chris F.
A: 

You could try using the enum column plugin to get this functionality.

Migration to create the table:

add_column :accounts, :status, :enum, :limit => [:submitted, :pending, :approved],
      :default => :submitted

In the model:

validates_columns :status

In the controller

@account = Account.new # It just works :)
galileoMonkey