Reputation: 1150
I am trying to update a rails model but I am facing some errors with the data handling even though the ajax request does go through.
The parameters being sent appears as shown below:
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"]]
Whereas a normal update does:
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"]]
I am not sure where I have gone wrong being new to Rails and JSON.
I have tried out solutions posted by How do I parse JSON with Ruby on Rails?. But after changing my codes the requests does not get sent out. I have also tried changing the data being sent by following certain examples but it didn't work out as well.
I would appreciate advice on what I could do to solve this error.
The following are the relevant codes:
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)
});
My controller update action:
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
I would appreciate any advice on where I might have gone wrong. Thanks!
Upvotes: 1
Views: 619
Reputation: 5474
update_attributes
expects a Hash. By converting the data you send to the server to JSON, params contains a JSON string instead. You should call the controller with standard POST data:
$.ajax({
type: "PUT",
url: url,
dataType: "json",
data: dataToServer
});
Upvotes: 2