ruby-on-railsrubytemplatesyieldcontent-for

Why content_for method undefined in rails view?


I have a rails project.

In the application.html.slim I have:

doctype html
html
  head
    title RailsMongoidPj
    = stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true
    = javascript_include_tag "application", "data-turbolinks-track" => true
    = csrf_meta_tags
    meta content="width=device-width, initial-scale=1.0" name="viewport"
    = yield(:html_head)
  body
    = yield

In a controller SearchController, which has a method:

  def javascript(*files)
    content_for(:html_head) do
      javascript_include_tag(*files)
    end
  end
  helper_method :javascript

Also this controller has a method new with a corresponding view, which content is:

= javascript('/vendor/assets/javascript/handelbars.runtime.js')

- content_for :html_head do
  script#entry-template type="text/x-handlebars-template"
    | template content

But I have an error:

undefined method `content_for' for #<SearchFlickrController:0x007f8e4f2bae78>

Extracted source (around line #3):

1  / search flickr api page
2  
3  = javascript('/vendor/assets/javascript/handelbars.runtime.js')
4  
5  - content_for :html_head do
6    script#entry-template type="text/x-handlebars-template"

Why the method is content_for undefined? Isn't it an standard rails method?


Solution

  • content_for is a helper method. You use content_for in a view, not in a controller. Therefore the right place for a method using content_for is a helper (app/helper/search_helper.rb for example):

    module SearchHelper  
      def javascript(*files)
        content_for(:html_head) do
          javascript_include_tag(*files)
        end
      end
    end