Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a model's integer attribute to a string?

I have a Hotels table in my database, and one of the columns is :status (integer). I'm looking to convert these integers into strings, so 1 = "Awaiting Contract", 2 = "Designing" and so on...

I have searched Stack for some answers, and the lack of them makes me think that I'm coming at this problem from the wrong angle? I used to do this in PHP whilst pulling the data. New-ish to Rails so any help, or best practise advice would be much appreciated.

like image 737
ItsJoeTurner Avatar asked Dec 20 '22 05:12

ItsJoeTurner


1 Answers

Check enum of ActiveRecord - doc.

Here you can configure your :status:

class Hotel < ActiveRecord::Base
  enum status: { waiting_contract: 1, designing: 2 }

  def format_status
    status.to_s.humanize
  end
end

It'll create methods like this:

hotel.waiting_contract?
hotel.designing?

hotel.waiting_contract!
hotel.format_status # => "Waiting contract"

Hope that helps!

UPDATE

Similar functionality might be achieved by overriding the status method itself, although having separate methods is more advised:

class Hotel < ActiveRecord::Base
  enum status: { waiting_contract: 1, designing: 2 }

  def status
    super.to_s.humanize
  end
end

Furthermore, decorators are something you should look into for view-specific methods.

like image 53
Paweł Dawczak Avatar answered Dec 26 '22 17:12

Paweł Dawczak