Undefined method when creating a helper in Rails

穿精又带淫゛_ 提交于 2020-01-24 20:15:10

问题


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

  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

In application_helper.rb:

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

In the layout work.html.erb:

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

回答1:


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

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

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


来源:https://stackoverflow.com/questions/17770419/undefined-method-when-creating-a-helper-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!