[英]Access a view helper for a model in rails
I have an Adult model with a name attribute. 我有一个带有name属性的Adult模型。
If the user is logged in, I want the Adult.name to only return the first name. 如果用户已登录,我希望Adult.name仅返回名字。
Is there a way to have helpers tied to a model where you could specify Adult.helper.name? 有没有办法将帮助器绑定到您可以指定Adult.helper.name的模型?
Or a least have helpers namespaced to a model? 或者至少将帮助者命名为模型?
Just explicitly include the helper in your model 只需在模型中明确包含帮助器即可
# app/helpers/adults_helper.rb
module AdultsHelper
def say_hello
"hello, world!"
end
end
# app/models/adult.rb
class Adult < ActiveRecord::Base
include AdultsHelper
end
Test in console 在控制台中测试
$ script/console
>> a = Adult.new
# => #<Adult id:...>
>> a.say_hello
# => "hello, world!"
in your Adult model you can add 在您的成人模型中,您可以添加
def name
self.first_name
end
so when you find an Adult, like 所以当你找到一个成年人时,就像
a = Adult.last
puts a.name #will print a.first_name
Well, for a better explanation.. paste some code! 好吧,为了更好的解释..粘贴一些代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.