views:

93

answers:

3

I haven't been able to find documentation that talk about how create.js.erb and destroy.js.erb fit in a Rails 3 app.

What is the logic behind these types of Javascript files in the app > controllers? How and when are they accessed?

+1  A: 

When you access your action via XMLHttpRequest for example, your action will respond with a javascript file.

In your controller:

class MyController < ApplicationController

  respond_to :html, :js

  def show
    @my_model = MyModel.find(params[:id])

    respond_with @my_model
  end

end

The show action will respond with the html view when accessed via html, and with je js view when accessed via XMLHttpRequest.

Yannis
@Yannis, thanks that's very helpful. I get it now... What is I want to load an entire tab's contents? Like in Facebook when you click the photos tabs, it doesn't refresh the page. Rather the page loads in the photos tab content and injects the content in the page with AJAX... No page refresh. How is this done with Rails?
AnApprentice
+1  A: 

Basicly those are the views rendered in respond to ajax call. When you do a normal request, then, then controller is passing the varaialbes to your view, ie. create.html.erb. If you do an Ajax call to the controller, then the controller is rendereing create.js.erb.

The main difference is, that in the create.html.erb you should have a full template of your page. In case of create.js.erb you should have a javascript code which can modify your views.

For example:

$('#comments-box').html("<%= escape_javascript(index_comments(@commentable, @comments)) %>");
$('#comments-box-spinner').hide();
$('#flash').html("<%= escape_javascript(render(:partial => 'layouts/flash', :collection => flash)) %>");
mdrozdziel
+1  A: 

File extensions are associated with Mime types. Check my answer here. It was written for Rails 2.2.2, but the same logic still holds. Note that the respond_to syntax has changed in Rails 3.
Also, these files are not in app/controllers, but in app/views/<controller_name>/

Swanand