0
我有一個可以存儲答案和教訓列表的User
類如何更新,或創建的/對象放入集合
has_many :answers
has_many :lessons, :through => :answers
答案類:
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :lesson
attr_accessible :finished, :current_solution
end
每用戶上課的時間,我想存儲他的最新答案。我試圖做這樣的:
if current_user
@lesson = Lesson.find(params[:id])
@code = request.request_parameters["code"]
@user = User.find(session[:user_id])
begin # retrieve an old answer, if possible
@answer = Answer.find [params[:id], session[:user_id]]
rescue
end
if not @answer # else create a new one
@answer = Answer.new
@answer.lesson_id = @lesson.id
@answer.user_id = @user.id
@user.answers << @answer # store it in the user's answers list
end
@validation_passed = @lesson.validate(@code)
@answer.finished = @validation_passed # update answer
@answer.current_solution = @code
數據庫模式:
create_table "answers", :id => false, :force => true do |t|
t.integer "lesson_id", :null => false
t.integer "user_id", :null => false
t.string "finished"
t.string "current_solution"
end
add_index "answers", ["lesson_id", "user_id"], :name => "index_answers_on_lesson_id_and_user_id", :unique => true
我得到一個異常columns lesson_id, user_id are not unique
,或columns lesson_id, user_id are not unique: INSERT INTO "answers" ("current_solution", "finished", "lesson_id", "user_id") VALUES (?, ?, ?, ?)
,但我不明白爲什麼這會發生,因爲我只能創建新的對象,如果沒有找到與相應的座標..
如果有人能告訴我我做錯了什麼,我會很高興。
在此先感謝! :)
感謝這些不錯的方式來檢索答案:) exce ption現在不見了,但不幸的是,在字段answer.finished和answer.current_solution中所做的更改不會永久存儲......當我重新訪問我已經工作過的應用程序時,它們的內容不再存在:( – chris
正確 - 你需要調用'@ answer.save'(或者如果你不覺得自己很勇敢的話可以用'@ answer.save!')在你設置好數據庫之後提交這些更改 – PinnyM
我已經試過了,但是這個拋出異常'SQLite3 :: SQLException:沒有這樣的列:答案:更新「答案」SET「完成」='噸',「current_solution」='1'在哪裏「答案」。這IS NULL很奇怪.. – chris