在 rails 中访问模型的视图助手 [英] Access a view helper for a model in rails

查看:45
本文介绍了在 rails 中访问模型的视图助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 name 属性的 Adult 模型.

I have an Adult model with a name attribute.

如果用户已登录,我希望 Adult.name 只返回名字.

If the user is logged in, I want the Adult.name to only return the first name.

有没有办法将助手绑定到可以指定 Adult.helper.name 的模型?

Is there a way to have helpers tied to a model where you could specify 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

在控制台中测试

$ script/console
>> a = Adult.new
# => #<Adult id:...>
>> a.say_hello
# => "hello, world!"

这篇关于在 rails 中访问模型的视图助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆