开发者

Is it possible to render a js.erb without using the respond_to method and using an unconventional filename?

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:


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.


Partial files need to be named as with a underscore.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜