[英]Adding a custom method to a model attribute?
Is this any possible? 这有可能吗?
I'd like to have something like 我想要有类似的东西
User.avatar.to_url
which would then print the full URL address for the user's avatar image. 然后打印用户头像图像的完整URL地址。
=> "http://url.com/images/avatars/1262694724.jpeg"
Of course, the avatar attribute would be an existing column on the users table which contains a long integer. 当然,avatar属性将是users表上包含长整数的现有列。
The to_url method im thinking on would be defined as: 我想的to_url方法定义为:
def to_url
"http://url.com/images/avatars/#{self}.jpeg"
end
If avatar
is an attribute (as opposed to another model/association) then you're going to save yourself a world of trouble by just doing: 如果
avatar
是一个属性(而不是另一个模型/关联),那么你只需要通过以下方式为自己节省一个麻烦的世界:
def avatar_url
"http://url.com/images/avatars/#{avatar}.jpeg"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.