如何将模型的整数属性映射到字符串? [英] How to map a model's integer attribute to a string?
问题描述
我的数据库中有一个Hotels表,其中一列是:status
( integer
)。我想将这些整数转换为字符串,因此 1 =正在等待合同
, 2 =设计
等等...
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...
我已经在Stack上搜索了一些答案,而缺少答案的确使我觉得我从错误的角度来解决这个问题?我曾经在PHP中同时提取数据。
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.
推荐答案
检查
-文档。 ActiveRecord
的枚举
在这里您可以配置:status
:
class Hotel < ActiveRecord::Base
enum status: { waiting_contract: 1, designing: 2 }
def format_status
status.to_s.humanize
end
end
它将创建如下方法:
hotel.waiting_contract?
hotel.designing?
hotel.waiting_contract!
hotel.format_status # => "Waiting contract"
希望有帮助!
更新
相似的功能可能是通过覆盖 status
方法本身来实现的,
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.
这篇关于如何将模型的整数属性映射到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!