[英]Ruby on Rails function for model attribute
I have one active record model called Task
with following attributes: 我有一个称为
Task
活动记录模型,具有以下属性:
name (string)
due (date)
priority (int)
How do I create a function for priority so I can call it something like this 如何创建优先级函数,以便可以这样称呼它
@task.priority.to_str
would produce "Low", "High" based off the integer value @task.priority.to_str
会根据整数值产生“低”,“高”
I don't want to override the attribute method to print out the string because I need to access the actual value. 我不想覆盖属性方法以打印出字符串,因为我需要访问实际值。
You can add a new instance method: 您可以添加一个新的实例方法:
class Task
def str_priority
priority < 5 ? 'Low' : 'High'
end
end
@task.str_priority
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.