我想在Rails中使用事务方法,如果我的student_code
是nil
,那么它将引起回滚。
如果我的school_code
是nil
,那么它将用school_code
更新我的1
属性,如果不存在则更新。然后它将使用+1
进行更新,并使用teacher_code
和student_code
进行更新。
假设我的school_code = 1
和teacher_code
和student_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
。