Undefined method when creating a helper in Rails

I tried to create a helper module to be able to set the page title. Of course, it does not work ( link ) Is there something that I have to define in the controller for the methods of my assistants that my controllers will see?

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 

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
ruby-on-rails html-helper
Jul 21 '13 at 8:22
source share
1 answer

Helpers in Rails are methods available in views (and controllers if you enable them) that help you avoid repeating code in views.

An example of a helper from my code is a method that displays html for the facebook login button. This button is actually larger than the user sees, because it is 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 several 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 an <h1> heading at the top of the page.

Now I see that the related answer was not clear enough. You really need an assistant, but you also need to call! 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 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> 
+3
Jul 21 '13 at 8:25
source share



All Articles