1

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?

static
  • 8,126
  • 15
  • 63
  • 89

1 Answers1

2

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
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • do you know what to do to make it work and still having the method outside the view? I found this solution here: http://stackoverflow.com/questions/6571753/rails-3-1-asset-pipeline-how-to-load-controller-specific-scripts. – static Oct 02 '13 at 20:25