你如何从 Rails 的视图中调用方法? [英] How do you call a method from the view in rails?

查看:41
本文介绍了你如何从 Rails 的视图中调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我这样做了:

脚本/生成控制器主页

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

And in the home controller made a the method..

def say
  puts "You are here"
end

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

How would I call that method in the index.html.erb?

在学习 ruby​​ 时,它只是说在终端中运行whatever.rb运行您在该文件中编写的任何代码.只是好奇如何这将适用于导轨.

When learning ruby it just said to run the whatever.rb in the terminal to run what ever code you wrote within that file. Just curious on how that would work with rails.

推荐答案

我假设你有一个 Rails 服务器在运行?

I assume you have a rails server running?

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

Theres two possibilities, firstly you could make say a helper method in the controller by using:

helper_method :say

在您的控制器中.

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

Alternatively, the better solution would be move your say method to the home_helper(?).rb helper file.

您可以通过在视图文件中使用 <% say %> 来调用它.

you can call this by just using <% say %> in your view file.

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

Note that a puts well put whatever is in your string to STDOUT, not output in your views, if all you wanna do is write a bit of text, you would be better off with just outputting a string and using the erb output mechanism in your view, e.g.

application_helper.rb

application_helper.rb

def say
  "hello"
end

index.html.erb

index.html.erb

<%= say -%>

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

puts is very useful for unit test debugging where you wanna find out the contents of an object

puts @some_object.inspect

如果你想输出到日志,你可以这样做:

Whereas if you want output to the log, you could do something like:

logger.error "hello"

这篇关于你如何从 Rails 的视图中调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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