1. 方法跳过
使用下列方法可跳过回调:
decrement decrement_counter delete delete_all increment increment_counter
toggle touch update_column update_columns update_all update_counters
2. 跳过validate验证
保存的时候用validate: false
user.save(:validate => false)
3. create,save相关回调(ex: after_create, before_save)
例如以下代码 after_create回调
class User < ActiveRecord::Base after_create :send_email def send_email #send email to user end end
rails 提供skip_callback(name, *filter_list, &block)方法跳过回调。在执行完skip_callback后要执行set_callback方法恢复回调。
User.skip_callback(:create, :after, :send_email) user = User.new user.email = "xxxx" user.save User.set_callback(:create, :after, :send_email)
上面这种方法虽然可行,但是存在线程安全的问题。
下面是线程安全的跳过回调的方法。
class User < ActiveRecord::Base after_create :send_email, unless: :skip_send_email attr_accessor :skip_send_email def send_email #send email to user end end # 这样就会跳过回调 user = User.new user.skip_send_email = true user.email = "xxxx" user.save