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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With