Rails 请教各位大神个问题, create 的时候怎么跳过 before_create 呢

13684054420 · 2016年08月30日 · 最后由 mengqing 回复于 2016年08月31日 · 2603 次阅读

create 的时候怎么跳过 before_create 呢,,拜托各位大神啊

class Employee
    before_create  do 
      self.employee_category = self.employee.category.display_name
    end
end

class EmployeeImport
    Employee.create(hash)
end

EmployeeImport 里面的 create 怎么跳过 before_create 呢

before_create :do_something, if: :your_custom_condition

private

def your_custom_condition
  if you_do_not_want_to_do_something
    false
  else
    true
  end
end

使用 skip_callback 和 set_callback

Model.skip_callback(:create,:before,:do_something)
Model.set_callback(:create,:before,:do_something)

或者是这样

class Writer < Person
           skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
end

#2 楼 @jzlikewei

class Employee
    before_create  do 
      self.employee_category = self.employee.category.display_name
    end
end

class EmployeeImport
    Employee.create(hash)
end

EmployeeImport 里面的 create 是怎么跳过 before_create 的呢,,,,原谅我是个菜鸟吧😂

#3 楼 @13684054420

class Employee
    before_create  :set_category
    def set_category
      self.employee_category = self.employee.category.display_name
    end
end

class EmployeeImport
    Employee.skip_callback(:create,:before,:set_category)
    Employee.create(hash)
    Employee.set_callback(:create,:before,:set_category)
end

skip_before_action :xxx

then the function xxx will skip that before_action

class Employee
  attr_accessor  :skip_callback
  before_create  do 
    self.employee_category = employee.category.display_name unless skip_callback
  end
end

class EmployeeImport
  Employee.create(hash.merge(skip_callback: true)
end

这样的做法可能会更方便些

需要注意的是 skip_callback 和 set_callback 不是 thread safe

如果需要 thread safe 的话可以用https://github.com/partyearth/sneaky-save

需要 登录 后方可回复, 如果你还没有账号请 注册新账号