轨。如何更新模型

时间:2015-06-24 13:49:04

标签: ruby-on-rails activerecord

我有一种情况,用户可以申请工作(称为工作申请)。当作业的雇主接受/批准用户完成工作时,模型应自动检查用户是否在同一时间内有另一份工作。

1)如果有,它将发出一条错误消息,提示用户已有作业。这是由self.errors.add

完成的

2)应该将用户所有其他应用程序的状态设置为“User Already Booked”。

我能够做到1)没有任何问题,但是当我做2)SQL事务继续给我“回滚”。我首先得到了我想要更新的所有条目,然后我尝试使用update_all方法来更新它们。但是,数据库不会提交事务并继续给我回滚。

以下是我的代码。任何人都可以告诉我如何在模型中保存记录(不仅仅是'自我'而是其他条目)。或者至少如何调试该回滚消息。

#Inside my Job Application Model
#Run the custom validation I made
validate :does_user_have_job

private

#check if User have another job_application that overlaps with the current one
def does_user_have_job
  #pre define variables for easier understanding
  job = self.job
  id = job.id
  start_time = job.start_time
  end_time = job.end_time

  #This part is a query to the database to find whether there is overlap.
  #Please ignore this as this is not important.
  overlaps = self.user.job_applications.joins(:job).where.not(job_id: id).where(approved: true).where("(jobs.start_time >= ? AND jobs.start_time <= ?) OR (jobs.end_time <= ? AND jobs.end_time >= ?)", start_time, end_time, end_time, start_time)

  #if there are overlaps, then set the status of those overlaps to "User Already Booked"
  if not overlaps.empty?
    #Find the entries that I want to set status to
    #I am picking out these entries for testing purposes
    #Do not ask my why I am using application where approved = false 
    job_applications = self.user.job_applications.where(approved: false)

    #This is the first method I used but the transaction
    #got rollback therefore I used the second method
    #job_applications.update_all(status: "User Already Booked")

    #This is the second method I used but the transaction
    #still got rollback and error message was empty
    job_applications.each do |job_application|
      job_application.assign_attributes(status: "User Already Booked")
      job_application.save(validate: false)
      puts job_application.errors.messages
    end  #scroll down for more vvvvvv

    #Third method I tried as suggested by "steve klein"
    #Still got rollback
    job_applications.each do |job_application|
      job_application.update_attribute(:status, "User Already Booked")
    end

    #After setting the status of other entries I raise an error
    self.errors.add(:job_application, "User is already booked")
  end
end

我检查时出现的错误消息

SQL (0.1ms)  UPDATE "job_applications" SET "status" = ?, "updated_at" = ? WHERE "job_applications"."id" = ?  [["status", "Already Have Job"], ["updated_at", "2015-06-24 14:06:18.480217"], ["id", 72]]
<<< inspecting error
#<ActiveModel::Errors:0x007f9f3dc94378 @base=#<JobApplication id: 72, job_id: 70, user_id: 1, master_id: 1, status: "Already Have Job", user_reviewed: false, master_reviewed: false, started_user: false, ended_user: false, created_at: "2015-06-23 17:14:52", updated_at: "2015-06-24 14:06:18", approved: false>, @messages={}>
(1.0ms)  rollback transaction

0 个答案:

没有答案