控制器中的交易

时间:2019-05-30 11:25:23

标签: ruby-on-rails transactions ruby-on-rails-5

我想在Rails中使用事务方法,如果我的student_codenil,那么它将引起回滚。

如果我的school_codenil,那么它将用school_code更新我的1属性,如果不存在则更新。然后它将使用+1进行更新,并使用teacher_codestudent_code进行更新。

假设我的school_code = 1teacher_codestudent_code都等于2,那么它将用+1更新所有三个。

如果其中任何一个为nil,则应该提高回滚率。

我已经尝试过,但是它仅更新school_code

class PartialsController < ApplicationController
  def update_school_and_teacher_code
    School.transaction do 
       school = School.find_by_school_code(3)
       if school.school_code == 3
         school.update_attributes!(:school_code => 2)
         teacher = Teacher.update(:teacher_code => 2)
         student = Student.update(:student_code => 2)
       else
        raise ActiveRecord::Rollback
      end
    end
  end
end

,输出为:

   (0.2ms)  BEGIN
  School Load (0.2ms)  SELECT  "schools".* FROM "schools" WHERE "schools"."school_code" = $1 LIMIT $2  [["school_code", 3], ["LIMIT", 1]]
  School Update (0.4ms)  UPDATE "schools" SET "school_code" = $1, "updated_at" = $2 WHERE "schools"."id" = $3  [["school_code", 2], ["updated_at", "2019-05-30 11:05:30.040902"], ["id", 5]]
  Teacher Load (0.4ms)  SELECT "teachers".* FROM "teachers"
  Student Load (0.4ms)  SELECT "students".* FROM "students"
  Course Load (0.2ms)  SELECT  "courses".* FROM "courses" WHERE "courses"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Course Load (0.3ms)  SELECT  "courses".* FROM "courses" WHERE "courses"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
   (40.7ms)  COMMIT

这不是完全正确,它只是更新school_code

0 个答案:

没有答案