小编mca*_*mir的帖子

Rails 3 ActiveRecord .skip_callback线程安全

这段代码线程安全吗?

MyModel.skip_callback(:save, :before, :my_callback)
my_model_instance.update_attributes(attributes)
MyModel.set_callback(:save, :before, :my_callback)
Run Code Online (Sandbox Code Playgroud)

我可以安全地使用它来避免递归地重新触发相同的回调吗?

这是一个例子

class Blog < ActiveRecord::Base

  after_save  :update_blog_theme, :if => :active_theme_id_changed?

  # ...

  private

  def update_blog_theme

    # Reuses a previously used BlogTheme or creates a new one
    blog_theme = BlogTheme.find_by_theme_id_and_blog_id(
                      self.active_theme_id, 
                      self.id)

    blog_theme ||= BlogTheme.create!( 
                     :theme_id => active_theme_id, 
                     :blog_id => self.id )

    Blog.skip_callback(:save, :after, :update_blog_theme)
    self.update_attributes!(:active_blog_theme_id => blog_theme.id) 
    Blog.set_callback(:save, :after, :update_blog_theme)

  end

end
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails callback thread-safety ruby-on-rails-3

6
推荐指数
1
解决办法
1965
查看次数