访问rails中的模型的视图助手

Chr*_*her 4 ruby-on-rails

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

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

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

或者至少将帮助者命名为模型?

mač*_*ček 11

只需在模型中明确包含帮助器即可

# 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
Run Code Online (Sandbox Code Playgroud)

在控制台中测试

$ script/console
>> a = Adult.new
# => #<Adult id:...>
>> a.say_hello
# => "hello, world!"
Run Code Online (Sandbox Code Playgroud)