I’m having a strange issue here – I’m either sending the attributes wrong, or I’m doing something wrong on the Rails end. It looks like there’s more to do wrong on the javascript/jQuery side of things than the Rails side of things, so that one is more likely.
Anyways, here are the relevant pieces of code. My question is on the very bottom of this post.
The Controller Method
def update
@answer = Answer.find(params[:id])
@answer.update_attributes(params[:answer])
puts @answer.inspect
respond_to do |format|
format.html { render :json => Answer.find(params[:id]) }
end
end
The Javascript Function (jQuery is loaded)
function saveAnswer(question_number, answer_number)
{
console.log(JSON.stringify(window.questions[question_number].answers[answer_number]));
$.ajax(
{
type: 'POST',
url: "/answers/" + window.questions[question_number].answers[answer_number].id + "/update",
data: JSON.stringify(window.questions[question_number].answers[answer_number]),
});
}
The Output of the above console.log() function being called:
{"content":"Latte.ASDASD!!!! Z","created_at":"2011-08-15T20:01:48Z","graded":true,"id":9,"problem_id":2,"turned_in":true,"updated_at":"2011-08-22T06:42:20Z","user_id":1,"score":5}
WEBrick receiving the request:
Started POST "/answers/9/update" for 127.0.0.1 at 2011-08-21 23:44:10 -0700
Processing by AnswerController#update as */*
Parameters: {"content"=>"Latte.ASDASD!!!!       Z", "created_at"=>"2011-08-15T20:01:48Z", "graded"=>"true", "id"=>"9", "problem_id"=>"2", "turned_in"=>"true", "updated_at"=>"2011-08-22T06:42
:20Z", "user_id"=>"1", "score"=>"5"}
←[1m←[36mAnswer Load (0.0ms)←[0m ←[1mSELECT "answers".* FROM "answers" WHERE "answers"."id" = ? LIMIT 1←[0m [["id", "9"]]
←[1m←[35mCACHE (0.0ms)←[0m SELECT "answers".* FROM "answers" WHERE "answers"."id" = ? LIMIT 1
Completed 200 OK in 16ms (Views: 4.9ms | ActiveRecord: 0.0ms)
The Model’s Contents:
irb(main):007:0> Answer.inspect
=> "Answer(id: integer, problem_id: integer, user_id: integer, content: text, created_at: datetime, updated_at: datetime, turned_in: boolean, graded: boolean)"
How do I get Rails to update the attributes of the specified Answer model using the input from the saveAnswer function?
You’re missing the root element in the data field of your JSON request. Should be like: