在Rails中创建帮助程序时的未定义方法

时间:2013-07-21 08:22:20

标签: ruby-on-rails html-helper

我尝试创建一个帮助程序模块,以便能够设置页面的标题。当然它不起作用(reference)我必须在控制器中定义一些东西,我的控制器可以看到我的助手方法吗?

Undefined method

Gitlink:works_controller.rb

  def index
    set_title("Morning Harwood")
    @works = Work.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @works}
    end
  end

application_helper.rb中:

module ApplicationHelper
    def set_title(title = "Default title")
      content_for :title, title
    end  
end

在布局work.html.erb中:

 <%= content_for?(:title) ? content_for(:title) : 'This is a default title' %>

1 个答案:

答案 0 :(得分:3)

Rails中的助手是视图中可用的方法(如果包含它们,则为控制器),可以避免视图中的代码重复。

我的代码中的帮助程序示例是一个为facebook登录按钮呈现html的方法。这个按钮实际上比用户看到的更多,因为它是一个隐藏的形式,带有一些额外的信息,等等。因此我想用它做一个帮助方法,所以不是多次复制10行代码,我可以调用一个单一方法。这更干嘛。

现在,回到你的例子,你想做两件事

  • 显示页面<title>
  • 在页面顶部添加<h1>标题。

我现在看到链接的答案不够明确。你确实需要帮助,但你也需要打电话给它!所以

# application_helper.rb
def set_title(title = "Default title")
  content_for :title, title
end

# some_controller.rb
helper :application

def index
  set_title("Morning Harwood")
end

然后在布局的视图中,您可以使用:

<title> <%= content_for?(:title) ? content_for(:title) : 'This is a default title' %><</title>
...
<h1><%= content_for?(:title) ? content_for(:title) : 'This is a default title' %></h1>
相关问题