开发者

Rendering a different Javascript file in respond_to

I am stuck in an (apparently) simple problem. In my event_controller I have the i_like_it action:

  def i_like_it
    @event = Event.find(params[:id])

    ... # logic

    respond_to do |format|
      format.js
    end
 开发者_StackOverflow社区 end

In my case "i_like_it" is called with :method => PUT (it is an Ajax call, "i_like_it.js.erb" will be returned as a script and it wil be executed on the browser.)

I would like render a Javascript file with a different name (not i_like_it.js.erb) , but I haven't found any option in the Rails API docs.

respond_to do |format|
  format.js { render ??? }
end

Rails can render vanilla JavaScript with :js option, but I don't want use Javascript in the controller.

Do you have any suggestion ?

Thank you, Alessandro DS


If you do:

respond_to do |format|
  format.js { render :action => "different_action" }
end

it will load RAILS_ROOT/app/views/your-controller/different_action.js.erb instead.

The format.js block just ensures that if it's a .js request, you have the proper headers set by default and it looks for .js.erb or .js instead of .html.erb by default.

You can also use render :file to render any arbitrary file on the file system that happens to have JS in it, or you could use any of render's other usual options. There are a few of them.


Try render :template => 'your_file_here' instead of

respond_to do |format|
  format.js
end

Documentation for render describes a couple of other options too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜