如何从rails中的视图调用方法?

Aar*_*ron 9 ruby ruby-on-rails

假设我这样做了:

脚本/生成控制器主页

并在家庭控制器制作了一个方法..

def say
  puts "You are here"
end
Run Code Online (Sandbox Code Playgroud)

我如何在index.html.erb中调用该方法?

当学习ruby时,它只是说在终端中运行whatever.rb来运行你在该文件中编写的代码.只是好奇如何使用rails.

Oma*_*shi 17

我假设你有一个运行的rails服务器?

有两种可能性,首先你可以使用以下方法在控制器中说一个辅助方法:

helper_method :say
Run Code Online (Sandbox Code Playgroud)

在你的控制器中.

或者,更好的解决方案是将您的say方法移动到home_helper(?).rb帮助文件.

您只需在视图文件中使用<%say%>即可调用此方法.

请注意,puts将字符串中的任何内容放到STDOUT中,而不是在视图中输出,如果您只想写一些文本,最好只输出一个字符串并在视图中使用erb输出机制,例如

application_helper.rb

def say
  "hello"
end
Run Code Online (Sandbox Code Playgroud)

index.html.erb

<%= say -%>
Run Code Online (Sandbox Code Playgroud)

puts对于要查找对象内容的单元测试调试非常有用

puts @some_object.inspect
Run Code Online (Sandbox Code Playgroud)

如果您想要输出到日志,您可以执行以下操作:

logger.error "hello"
Run Code Online (Sandbox Code Playgroud)