的代碼味道,我敢肯定,我缺少一個幫手做一個簡單的 更新或類似下面的代碼片段創建查詢:更好的Rails代碼更新或創建子句?
@user_answer = current_user.user_answers.find_by_question_id(params[:a_question])
if @user_answer.nil?
@user_answer = current_user.user_answers.build({ :answer_id => params[:an_answer] , :question_id => params[:a_question] })
@user_answer.save
else
@user_answer.update_attributes(:answer_id => params[:an_answer])
@user_answer.save
end
只是一個小小的建議,你不需要在else塊作爲對的update_attributes呼籲保存方法反正會隱式保存對象。請看我的回答 –