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 (?, ?, ?, ?),但我不明白为什么会发生这种情况,因为我只创建一个新对象,如果找不到相应坐标的对象..

如果有人能告诉我我做错了什么,我会很高兴。

提前致谢!:)

4

1 回答 1

2

您查找Answerfrom 参数的查询不正确 - 它应该是:

@answer = Answer.find_by_lesson_id_and_user_id(@lesson.id, @user.id)

这样做时,您也可以跳过begin--块。rescueend

如果您搜索关联,您可以进一步简化这一点:

@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
于 2013-01-24T22:36:03.960 回答