Rails 4使用来自AJAX的JSON数据更新Active Record

时间:2015-08-19 15:58:42

标签: ajax json ruby-on-rails-4

我花了一些时间环顾四周,但似乎没有回答这个问题。任何帮助表示赞赏。

我将带有AJAX调用的JSON数据发送回我的Rails应用程序(无CORS)。

使用Javascript:

$.ajax({
        type: "POST",
        url: "/tasks/",
        data: JSON.stringify(res),
        datatype: "json",
        async: true
       });   

从浏览器控制台复制的JSON数据(res):

[{"task_id":"9","grid_position":[0,2,2,2,false]},{"task_id":"8","grid_position":[0,0,2,2,false]}]:

到目前为止一切顺利。

然后通过路线发送:

resources :tasks,               only: [:index, :update, :create, :destroy]

到Tasks Controller,我正在尝试访问更新操作:

def update
    @task = Task.find(params[:id])
    respond_to :html, :json
    if @task.update_attributes(task_params)
       flash[:success] = "Task updated"
        redirect_to @user
    else
    flash[:error] = "Task not saved! Please see guidance by form labels"
        redirect_to user_url(current_user)
    end
end

我无法访问Tasks Controller中的Update操作。我已经尝试更改URL,将POST更改为PUT,并且我感到难过。

服务器错误消息:

Started POST "/tasks" for 217.137.84.197 at 2015-08-19 15:25:25 +0000
Processing by TasksController#create as */*
  Parameters: {"{\"task_id\":\"9\",\"grid_position\":"=>{"0,2,2,2,false"=>{"},{\"task_id\":\"8\",\"grid_position\":"=>{"0,0,2,2,false"=>{"}"=>nil}}}}}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
Completed 400 Bad Request in 4ms (ActiveRecord: 0.1ms)

我可以理解,它正在寻找用户,因为它正在尝试创建一个必须具有用户ID的新任务。但是,我只想更新现有任务。

2 个答案:

答案 0 :(得分:1)

$.ajax({ type: "POST"

触发创建操作。

如果要更新任务,请使用

type: "PATCH"

答案 1 :(得分:0)

我已经解决了这个问题,但它花了我一天所以我认为我应该发布。感谢tangrufus提供了有用的指示。

的Javascript(jQuery的)

  $.ajax({
       type: "PATCH",
       contentType: 'application/json; charset=UTF-8',//very important for rails it seems
       dataType: 'json',
       url: taskURL,
       data: JSON.stringify(task),
       cache: false,
       });

JSON stringify也存在问题,因为它不会在数组中使用非数字值。另一天的问题。

在任务控制器

wrap_parameters format: [:json, :xml]

并且在params中你需要为Rails 4中的数组做出特殊限制(谁知道?)

def task_params
params.require(:task).permit(:id, :label, :address, :content, {:grid_position => []})
end
相关问题