使用JSON数据更新Rails模型错误



我正在尝试更新一个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。

我已经尝试了解决方案,我如何用Ruby on Rails解析JSON ?但是在更改代码后,请求没有发出。我也试过通过以下某些例子来改变正在发送的数据,但它没有奏效。

如果能告诉我如何解决这个错误,我将非常感谢。

相关代码如下:

My Ajax request:

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
如果你能告诉我哪里做错了,我会很感激的。谢谢!

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

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

相关内容

  • 没有找到相关文章

最新更新