我有一个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 (?, ?, ?, ?)
,但我不明白为什么会发生这种情况,因为我只创建一个新对象,如果找不到相应的坐标.. < / p>
如果有人能告诉我我做错了什么,我会很高兴。
提前致谢! :)
答案 0 :(得分:2)
从params中查找Answer
的查询不正确 - 应该是:
@answer = Answer.find_by_lesson_id_and_user_id(@lesson.id, @user.id)
您也可以通过这种方式跳过begin
- rescue
- end
阻止。
如果你搜索关联,你可以进一步简化这个:
@answer = @user.answers.where(:lesson_id => @lesson).first
此外,如果这是一个常见的查找,您可以将范围添加到Answer
类:
class Answer < ActiveRecord::Base
scope :for_lesson, lambda{ |lesson| where(:lesson_id => lesson) }
end
然后你可以将其简化为:
@answer = @user.answers.for_lesson(@lesson).first