我正在尝试更新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
我很感激有关我可能出错的地方的任何建议。谢谢!
答案 0 :(得分:1)
update_attributes
期待哈希。通过将发送到服务器的数据转换为JSON,params包含一个JSON字符串。您应该使用标准POST数据调用控制器:
$.ajax({
type: "PUT",
url: url,
dataType: "json",
data: dataToServer
});