在Rails中创建助手时的未定义方法 [英] Undefined method when creating a helper in Rails

查看:73
本文介绍了在Rails中创建助手时的未定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个帮助器模块以能够设置页面标题.当然不起作用(参考)是否存在我必须在控制器中定义一些东西,以便控制器可以看到我的助手方法?

I tried to create a helper module to be able to set the title of a page. Of course it's not working (reference) Is there something I must define in a controller for my helpers methods to be seen by my controllers??

Gitlink: works_controller.rb

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' %>

推荐答案

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

Helpers in Rails are methods available in views (and controllers if you include them) that allow you to avoid code repetition in views.

我代码中的一个帮助器示例是一种为Facebook登录按钮呈现html的方法.实际上,此按钮比用户看到的要多得多,因为它是带有一些其他信息的隐藏表单,因此,我想以此为基础创建一个辅助方法,因此不必多次复制10行代码,而可以调用a单一方法.这更干了.

An example of a helper from my code is a method that renders html for facebook login button. This button is in reality more than user sees, because it's a hidden form with some additional information, etc. For this reason I wanted to make a helper method out of it, so instead of copying 10 lines of code multiple times I can call a single method. This is more DRY.

现在,回到您的示例,您想做两件事

Now, back to your example, you want to do two things

  • 显示页面<title>
  • 在页面顶部添加<h1>标头.
  • display page <title>,
  • add <h1> header at the top of the page.

我现在看到链接的答案还不够清楚.您确实需要帮助者,但是您也需要调用它!所以

I see now where linked answer wasn't clear enough. You indeed need helper, but you also need to call it! So

# 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

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

And then in layout's views you can use:

<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>

这篇关于在Rails中创建助手时的未定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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