helper_method 很简单:它使部分或全部控制器的方法可用于视图.
什么是helper?是否相反,即它将辅助方法导入文件或模块?(也许是名字helper和helper_method相似.他们可能更愿意share_methods_with_view和import_methods_from_view)
假设我这样做了:
脚本/生成控制器主页
并在家庭控制器制作了一个方法..
def say
puts "You are here"
end
Run Code Online (Sandbox Code Playgroud)
我如何在index.html.erb中调用该方法?
当学习ruby时,它只是说在终端中运行whatever.rb来运行你在该文件中编写的代码.只是好奇如何使用rails.
我有一个带有两个块的ERB视图:
<%= test_h1 do %>
<%= 'test1' %>
<% end -%>
<%= test_h2 do %>
<%= 'test2' %>
<% end -%>
Run Code Online (Sandbox Code Playgroud)
where test_h1和test_h2是类似的帮助器,但是一个在辅助文件中定义,而另一个helper_method在控制器中定义:
module TestHelper
def test_h1(&block)
link_to '/url' do
capture(&block)
end
end
end
class TestController < ApplicationController
helper_method :test_h2
def test_h2(&block)
helpers.link_to '/url' do
helpers.capture(&block)
end
end
end
Run Code Online (Sandbox Code Playgroud)
test_h1生成预期结果并首先test_h2渲染内部模板块:
<a href="/url">test1</a>
test2<a href="/url"></a>
Run Code Online (Sandbox Code Playgroud)
为什么?什么是惯用的写作方式test_h2?
我对红宝石很新.我有一个疑问,如何从视图中调用控制器方法.
我的控制器
def course_user_count
@courses=Course.all
@courses.each do |course|
@count=course.students.count
end
Run Code Online (Sandbox Code Playgroud)
我必须从我的视图course.view.html.erb中的方法中调用这个@count变量