vendredi 11 septembre 2015

Rails server returning HTML as opposed to JavaScript

There is the following link_to helper in my users/show.html.erb template:

<div id="social">
  <%= link_to "Friends", index_friends_path, id: "index_friends", remote: true %>
</div>

Since the value of :remote is set to true, my expectation was that the server would naturally try to return JavaScript with the AJAX response.

However, each time the link is clicked the response contains a file called users/friends.html.erb rather than a partial called users/_friends.html.erb which would be the required behaviour.

My code for handling the request is as follows:

--Routes in routes.rb:

get '/index_friends' => 'users#friends'

--Controller users_controller.rb:

def friends
  ...

  respond_to do |format|
    format.js
    format.html
  end
end

To try and fix this problem I also attached an event handler to the link so I could specify the requested dataType option explicitly as follows:

$('#social').on('click', '#index_friends', function() {
  index('/index_friends');
});

function index(url) {
  $.ajax({
    type: 'GET',
    url: url,
    dataType: 'script'
  });
};

But the server still responds with HTML not JavaScript.

Aucun commentaire:

Enregistrer un commentaire