Objective
Initialize a new addition problem for users to solve when they visit /task. They input their answer, and the form submits back to /task. The new action should initialize the problem, since users cannot edit the problem, only provide an answer. The create action should update the table addition_tasks in the column answer with the user’s submitted answer.
Problem
As I currently have it, the task is created and saved successfully in the new action, but fails to update with the create action.
Model
# == Schema Information
#
# Table name: addition_tasks
#
# id :integer not null, primary key
# first_addend :integer
# second_addend :integer
# sum :integer
# answer :integer
# correct :boolean
# created_at :datetime not null
# updated_at :datetime not null
#
class AdditionTask < ActiveRecord::Base
attr_accessible :answer
belongs_to :user
end
Routes
match 'task', to: 'addition_task#new'
match 'task', to: 'addition_task#create'
Controller
class AdditionTaskController < ApplicationController
respond_to :html, :js
def new
@task = AdditionTask.new
@task = new_task(@task)
@task.save
session[:task_id] = @task.id
end
def create
@task = AdditionTask.find(session[:task_id])
@task.answer = params[:addition_task][:answer]
respond_with :new
end
private
def new_task(task)
@task.first_addend = 1 + Random.rand(98)
@task.second_addend = 1 + Random.rand(98)
@task.sum = @task.first_addend + @task.second_addend
@task
end
end
View
%h1 Problem
:markdown
Please answer the question below. You may press "Enter" from within the answer field, instead of clicking the button, in order to receive a new question.
#task-container
.addend
=@task.first_addend
.operator
+
.addend
=@task.second_addend
.operator
\=
.answer
=simple_form_for @task, url: task_path, defaults: {input_html: {class: 'span2'}}, html: { class: 'form-inline' } do |f|
=f.input :answer, label: false
=f.submit :submit, class: 'btn-primary btn-large pull-right', value: 'Answer'
%div
=@task.sum
Siwei’s answer and lee’s answer both made excellent points.
Thanks to some folks in #rubyonrails, I moved the code from
createtoupdate. I also changed my routes, as Siwei suggested, and saved the object, as lee suggested. However, I used@obj.save!in order to get some helpful errors if something went wrong.New Routes
New Controller