406 Not Acceptable error on jQuery :remote => true link

1.5k views Asked by At

I am submitting a delete request through an anchor tag link, and using :remote => true to submit it via JS to use jQuery. I've done this in two other instances which are identical to this, with no problem at all. But for some reason, this one is causing problems - whenever I submit I get a 406 Not Acceptable error.

the destroy link

content_tag( :p, link_to("+#{vote.weight}", unvote_path(vote), :method => :delete, :remote => true ), :class => "chosen" )

routes.rb

delete "/unvote" => "votes#destroy", :as => :unvote

votes_controller.rb

def destroy
    @vote = Vote.find(params[:format])
    if !current_user.owns(@vote)
      flash[:alert] = "You cannot remove votes that aren't yours!"
    end
    @idea = @vote.idea
    @vote.destroy

    respond_with @vote do |format|
      format.js
      format.html { redirect_to category_idea_path(@idea.category, @idea) }
    end
end

destroy.js.erb

$('#vote_buttons').append('<%= escape_javascript get_vote_buttons(@idea.category, current_user, @idea) %>');

That's exactly the same line that I have in new.js.erb, and that works fine (apart from the fact that it doesn't return exactly what I want, but it at least executes and appends correctly).

application.js

jQuery.ajaxSetup({
    'beforeSend': function(xhr) { 
        xhr.setRequestHeader("Accept", "text/javascript");
    },
    cache: false
 });

And I've got that in application.js which should be setting the headers correctly, if I understand right.

Also, please note that the link performs its delete functionality correctly - when I refresh the page manually, the Vote has been deleted. The only problem seems to be with the content being returned by destroy.js.erb

Any idea why this is acting differently to my other working examples? I've been beating my head against this all day and can't figure it out.

1

There are 1 answers

1
StefanS On BEST ANSWER

Don't you have to add an :method => :delete to your destroy link? Also you probably don't want to use new_category_idea_vote_path for generating the destroy link but instead just category_idea_vote_path

Like that:

content_tag( :p, link_to("+#{i}", category_idea_vote_path(category, idea, :weight => i), :remote => true, :method => :delete ), :class => "valid" )

See this example:

  link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")

on http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to