Class: Spree::Taxons::AddProducts

Inherits:
Object
  • Object
show all
Includes:
ServiceModule::Base
Defined in:
app/services/spree/taxons/add_products.rb

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(taxons:, products:) ⇒ Spree::ServiceModule::Base::Result

Creates classifications for the given taxons and products in bulk.

Parameters:

Returns:

  • (Spree::ServiceModule::Base::Result)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/services/spree/taxons/add_products.rb', line 11

def call(taxons:, products:)
  return if taxons.blank? || products.blank?

  # build the params for the insert_all
  classifications_params = taxons.pluck(:id).flat_map do |taxon_id|
    position = Spree::Classification.where(taxon_id: taxon_id).count

    products.pluck(:id).map do |product_id|
      {
        taxon_id: taxon_id,
        product_id: product_id,
        position: (position += 1),
        created_at: Time.current,
        updated_at: Time.current
      }
    end
  end
  # doing a quick insert_all here to avoid the overhead of instantiating
  Spree::Classification.insert_all(classifications_params)

  # clearing cache
  Spree::Product.where(id: products.pluck(:id)).touch_all

  taxon_ids = taxons.pluck(:id)
  Spree::Taxon.where(id: taxon_ids).touch_all
  Spree::Taxons::TouchFeaturedSections.call(taxon_ids: taxon_ids)

  success(true)
end