Subsequent attribute calculations with a queue system

For all of the following, suppose the following:

  • rails v3.0
  • ruby v1.9
  • rescue

We have 3 models:

  • Product belongs to: sku, belongs_to: category
  • Sku has_many: products, belongs to_to : category
  • Category has_many: products, has_many: skus

When we update a product (for example, we turned it off), we need to have some things related to the corresponding category and category. The same is true when updating sku.

The correct way to achieve this is to have after_savefor each model that fires update events of other models.

Example:

products.each(&:disable!)
# after_save triggers self.sku.products_updated
#   and self.category.products_updated (self is product)

, 5000 , . .

, products.each(&:queue_disable!), 5000 . 5000 .

db?

.products_updated ?

+5
2

, Resque: Resque Unique Job Resque Scheduler.

, ( , , , ), , , Unique Job. , , 2 category_id 123, , .

class Product
  after_save :queue_category_update

  def queue_category_update
    Resque.enqueue_at(1.minute.from_now, Jobs::UpdateCategory, category.id) if need_to_update_category?
  end
end

module Jobs
  module UpdateCategory
    include Resque::Plugins::UniqueJob

    def self.perform(category_id)
      category = Category.find_by_id(category_id)
      category.update_some_stuff if category
    end
  end
end
+2

SQL. # update_all . ,

after_update :

class Category
  after_update :update_dependent_products

  def update_dependent_products
    products.update_all(disabled: disabled?) if disabled_changed?
  end
end

, resque:

class Category
  after_update :queue_update_dependent_products

  def update_dependent_products
    products.update_all(disabled: disabled?) if disabled_changed?
  end      

  def queue_update_dependent_products
    Resque.enqueue(Jobs::UpdateCategoryDependencies, self.id) if disabled_changed?
  end
end

class Jobs::UpdateCategoryDependencies
  def self.perform(category_id)
    category = Category.find_by_id(category_id)
    category.update_dependent_products if category
  end
end

.

0

All Articles