1

我正在尝试更新 rails 模型,但即使 ajax 请求确实通过了,我也面临一些数据处理错误。

正在发送的参数如下图所示:

Parameters: {"{\"slot_allocation\":{\"timeslot_id\":\"3\",\"subject_id\":\"3\",\"slot_allocation_id\":\"1\",\"group_index\
":\"Group 2\",\"lesson_type\":\"Tutorial\"}}"=>nil, "id"=>"1"}
  SlotAllocation Load (0.2ms)  SELECT "slot_allocations".* FROM "slot_allocations" WHERE "slot_allocations"."id" = ? LIMIT 1
  [["id", "1"]]

而正常更新会:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"yBib4ftNdB/r25uZuGnqEZI+r9dulVhyoce8nWBfcBQ=", "slot_allocation"=>{"slot_
allocation_id"=>"1", "lesson_type"=>"Lecture", "group_index"=>"Group 1", "timeslot_id"=>"1", "subject_id"=>"1"}, "commit"=>"
Update Slot allocation", "id"=>"1"}
  SlotAllocation Load (0.3ms)  SELECT "slot_allocations".* FROM "slot_allocations" WHERE "slot_allocations"."id" = ? LIMIT 1
  [["id", "1"]]

我不确定作为 Rails 和 JSON 的新手我哪里出错了。

我已经尝试过How do I parse JSON with Ruby on Rails? 发布的解决方案?. 但是在更改我的代码后,请求不会被发送出去。我也尝试按照某些示例更改发送的数据,但也没有成功。

我将不胜感激有关如何解决此错误的建议。

以下是相关代码:

我的 Ajax 请求:

var url = 'slot_allocations/'+alloc_id;

var dataToServer = {"slot_allocation":{"timeslot_id":timeslot, "subject_id":subject,"slot_allocation_id":alloc_id, "group_index":"Group 2", "lesson_type":"Tutorial"}}

  $.ajax({
    type: "PUT",
    url: url, 
    dataType: "json",
    data: JSON.stringify(dataToServer) 
    });

我的控制器更新操作:

  def update
    @slot_allocation = SlotAllocation.find(params[:id])

    respond_to do |format|
     if @slot_allocation.update_attributes(params[:slot_allocation])
        format.html { redirect_to @slot_allocation, notice: 'Slot allocation was successfully updated.' }
        format.json { head :ok}
      else
        format.html { render action: "edit" }
        format.json { render json: @slot_allocation.errors, status: :unprocessable_entity }
        format.js  { render :js => @slot_allocation.errors, :status => :unprocessable_entity }
      end
    end
  end

我将不胜感激任何关于我可能出错的地方的建议。谢谢!

4

1 回答 1

2

update_attributes需要一个哈希。通过将您发送到服务器的数据转换为 JSON,params 包含一个 JSON 字符串。您应该使用标准 POST 数据调用控制器:

$.ajax({
  type: "PUT",
  url: url, 
  dataType: "json",
  data: dataToServer
});
于 2013-01-01T14:41:01.163 回答