404调用jQuery.post时出错

时间:2015-02-26 23:22:54

标签: javascript jquery ruby-on-rails ruby jquery-post

我正在尝试使用我的rails应用程序中的jquery.post。结果我收到404(未找到)错误。

错误

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

更新

我更新了代码以遵循@maxd建议。我在rails视图中没有得到的错误是

POST http://localhost:3000/user_versions/create/1/3 500(内部服务器错误)jquery.js?body = 1:9632 jQuery.ajaxTransport.sendjquery.js?body = 1:9177 jQuery.extend.ajaxjquery.js?body = 1:9323 jQuery.each.jQuery。(匿名函数)apps.js?body = 1:53(匿名函数)jquery.js?body = 1:4642 jQuery.event.dispatchjquery.js?body = 1:4310 jQuery.event.add .elemData.handle

当我在Postman中调用相同内容时,它会获得422无法处理的实体状态

2 个答案:

答案 0 :(得分:1)

1)尝试从/

中删除... to: 'user_versions/#create'

2)检查网址路径使用rake routes | grep user_versions

答案 1 :(得分:1)

路径应为'/ user_versions / create',并将数据发布到对象中,如:

var data = {
    user_id: user_id,
    version_id: build
};
$.post( path, data, function( data ) {
    console.log(data);
});