Search code examples
javascriptjqueryruby-on-railsrubyjquery-post

404 Error when calling jQuery.post


I'm trying to us jquery.post in my rails application. I am getting a 404 (not found) error as a result.

error

POST http://localhost:3000/user_versions/create/1/13/ 404 (Not
Found)jquery.js?body=1:9632
jQuery.ajaxTransport.sendjquery.js?body=1:9177
jQuery.extend.ajaxjquery.js?body=1:9323 jQuery.each.jQuery.(anonymous
function)apps.js?body=1:53 (anonymous function)jquery.js?body=1:4642
jQuery.event.dispatchjquery.js?body=1:4310
jQuery.event.add.elemData.handle

routes.rb

post 'user_versions/create/:user_id/:version_id', to: 'user_versions#create'

apps.js.erb

$('.download-btn').on('click', function(e){
  e.preventDefault();
  var build = $(this).data('build');
  var user_id = $('#current_user_id').val();
  console.log(build);
  console.log(user_id);
  var path = "/user_versions/create/" + user_id + "/" + build + "/";
  $.post( path, function( data ) {
    console.log(data);
  });
});

user_versions_controller.rb

class UserVersionsController < ApplicationController
  def create
    user = params[:user_id]
    version = params[:version_id]
    UserVersion.find_or_create_by(user: user, version: version)
    render text: "success"
  end
end

UPDATE

I updated the code to follow @maxd suggestion. The error that I am not getting in the rails view is

POST http://localhost:3000/user_versions/create/1/3 500 (Internal Server Error)jquery.js?body=1:9632 jQuery.ajaxTransport.sendjquery.js?body=1:9177 jQuery.extend.ajaxjquery.js?body=1:9323 jQuery.each.jQuery.(anonymous function)apps.js?body=1:53 (anonymous function)jquery.js?body=1:4642 jQuery.event.dispatchjquery.js?body=1:4310 jQuery.event.add.elemData.handle

When I call the same in Postman it get a 422 Unprocessable Entity Status


Solution

  • 1) Try to remove / from ... to: 'user_versions/#create'

    2) Check URL path use rake routes | grep user_versions.