3

Is it possible to render a js.erb in response to an AJAX request without using the respond_to method?

I am asking because of a few reasons:

  1. I will only be making AJAX calls to my controllers;
  2. I will not be supporting any other content types (i.e., :html, :xml, etc.); and
  3. I want to be able to render a different js.erb file, not one named the same as the controller method (i.e., different.js.erb)

Here is some code to serve as an example.

app/views/posts/awesome.js.erb:

alert("WOOHOO");

PostsController#create

def create
  @post = Post.new(params[:task])
  if @post.save 
    render :partial => 'awesome.js.erb'
  end
end

When the create method is called via AJAX, Rails complains about a partial missing:

ActionView::MissingTemplate (Missing partial post/awesome.js, application/awesome.js with {:handlers=>[:erb, :builder, :coffee, :haml], :formats=>[:js, "application/ecmascript", "application/x-ecmascript", :html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json], :locale=>[:en, :en]}. Searched in:
John
  • 9,254
  • 12
  • 54
  • 75

2 Answers2

5

While Kieber S. answer is correct, here is another method that I think would be valuable for those who want to support the "conventional" method of creating js.erb files.

Instead of using render :partial use render :template. The caveat here, however, is that the search path for the template isn't automatically scoped to the name of the controller (i.e., app/views/posts). Instead, Rails starts at app/views/. So to reference the "template", you need to add the subfolder you want to look into, if it isn't in the root. In my case, I had to add posts.

def create
  @post = Post.new(params[:task])
  if @post.save 
    # using :template and added 'posts/' to path
    render :template => 'posts/awesome.js.erb'
  end
end

The benefit here is that if you should so happen to want to use the respond_to method and follow convention, you wouldn't need to rename your js.erb by removing the underscore.

John
  • 9,254
  • 12
  • 54
  • 75
3

Partial files need to be named as with a underscore.

Try to rename your partial to app/views/posts/_awesome.js.erb

Kleber S.
  • 8,110
  • 6
  • 43
  • 69
  • Ah, I figured as much. It seems a bit odd that there are two naming conventions for doing the same thing. For example, now if I use the `respond_to` method with `_awesome.js.erb`, Rails complains with the same message, except is saying `Missing template` instead of `Missing partial`... That gives me an idea. – John Aug 29 '11 at 05:19