[英]Relate Rails function/method to html.erb
I'm a newby in Rails, and trying to use methods in html.erb instead of writing the same query several times. 我是Rails的newby,并且尝试使用html.erb中的方法,而不是多次编写相同的查询。 I've started with "Hello, World";
我从“你好,世界”开始; but, I couldn't even manage to do this.
但是,我什至无法做到这一点。 What I do;
我所做的;
def Say()
"Hello World"
end
in app/models/sample.rb (sample is the name of the page by the way) and 在app / models / sample.rb中(顺便说一句,sample是页面的名称),
<% Say %>
in views/samples/index.html.erb. 在views / samples / index.html.erb中。 The problem is, obviously, I cannot see anything like "Hello World" on the page.
问题显然是,我在页面上看不到“ Hello World”之类的东西。 What should I do?
我该怎么办?
There are a number of things here: 这里有很多事情:
@say = 'Hello World'
in a controller method def index
and then calling in view <%= @say %>
will also do the trick, but don't get used to this approach as it commonly leads to bad habits like overuse of controller instead of models and helpers def index
添加@say = 'Hello World'
,然后在视图<%= @say %>
调用也可以解决问题,但不要习惯这种方法,因为它通常会导致不良习惯,例如过度使用控制器而不是模型和助手 Maybe the best is to start tutorials from scratch and see how it is handled in rails. 也许最好的方法是从头开始教程,并了解如何在Rails中处理它。 There are a lots of resources in rails on website: http://railscasts.com .
网站上的rails中有很多资源: http : //railscasts.com 。
Even the site hasn't been updated for quite some time, I think the best resource is to start from there, especially for newbies. 即使该网站已经有一段时间没有更新了,我认为最好的资源还是从那里开始,特别是对于新手。
There is helpers directory. 有助手目录。 You can create your own modules there or use default one: ApplicationHelper, which should exists in this dir.
您可以在此处创建自己的模块,也可以使用默认模块:ApplicationHelper,该模块应存在于此目录中。 Let's create your own module.
让我们创建自己的模块。
The following makes the Say helper method available to the view: 下面使说说帮助方法可用于视图:
module MyCustomHelper
def say
"Hello World"
end
end
In a view: 在视图中:
<%= say %>
Add helper module in your controller like(Rails 3): 在控制器中添加辅助模块,如(Rails 3):
class ApplicationController < ActionController::Base
helper :my_custom
end
or 要么
class ApplicationController < ActionController::Base
helper_method :my_custom
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.