我有一个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 (?, ?, ?, ?)
,但我不明白为什么会发生这种情况,因为我只创建一个新对象,如果找不到相应坐标的对象..
如果有人能告诉我我做错了什么,我会很高兴。
提前致谢!:)