Steve
Steve

Reputation: 4566

.js file being called without respond_to

I have a ratings controller whose create action gets called via Javascript. I have a create.js file in my ratings folder. I thought in order for the create.js file to be called you needed something like this

respond_to do |format|
    format.js
end

When I remove this however the create.js file is still being called. Is this because create.js is being called within the create action (i.e. the name of the method and .js file match)? Thanks!

Update: When format.js is missing, it cannot find the elements of the DOM. For example, if I have something like

$('#id_3').html('<%=escape_javascript render(:partial => 'show') %>');

The partial 'show' gets executed as I can see in the terminal but it cannot find the div 'id_3' and thus the partial never appears in the DOM. Any clarity would be appreciated, thanks

Upvotes: 1

Views: 153

Answers (2)

Henrique Zambon
Henrique Zambon

Reputation: 1301

That's how Rails works: it renders the view that has the same name as the action.

If you have multiple views with the same name (in different formats), you have to specify which one you want in the request and use the respond_to method to respond accordingly:

def index
  respond_to do |format|
    format.js { ... }
    format.html { ... }
    ...
  end
end

GET /index.html will render the index.html.erb file (assuming you're using ERB)

GET /index.js will render the index.js.erb file

Upvotes: 1

Luke W
Luke W

Reputation: 8934

Rails magic! If the link to your resource is something like /dogs/1.js, then respond_to handles it as you imagine. Try calling /dogs/1 and see what happens. Still works? Now try adding format.html before format.js. That should give you a good idea of how respond_to works.

Upvotes: 2

Related Questions