Search code examples
ruby-on-railsrubyapishopifysmartcollection

Loop for editing shopify collections


I'm pretty new to Ruby scripting and have made a script to loop through product collections in Shopify to change the 'product match condition' on all collections but I can't seem to get it to work at all unless I specify the collection ID.

I keep getting an error saying "NoMethodError: undefined method `disjunctive=' for #" and I can't figure out why. The script I've written is below:

Failed collection loop:

count = ShopifyAPI::SmartCollection.count
page = 1 
while count > 0
  collectionsEdits = ShopifyAPI::SmartCollection.find(:all,:params => {:page=> page})
  collectionsEdits.disjunctive = 'true'
  collectionsEdits.save
  count = count - 50
  page = page + 1
end

Specific collection ID:

collectionUpdate = ShopifyAPI::SmartCollection.find(437592964)
collectionUpdate.disjunctive = 'true'
collectionUpdate.save

Any help would be greatly appreciated!

API Documentation: https://help.shopify.com/api/reference/smartcollection


Solution

  • if Shopify::SmartCollection is just an ActiveRecord model so I'd recommend you to write that like this:

    ShopifyAPI::SmartCollection.where(page: page).update_all(disjunctive: 'true')
    

    P.S. in where clause you could provide any hash with your conditions

    In your case error occurs because find(:all) return a collection but not a single instance that's why you cannot execute disjunctive = 'true'

    So if you still want to write that your way do it like this:

    count = ShopifyAPI::SmartCollection.count
    page = 1 
    while count > 0
      collectionsEdits = ShopifyAPI::SmartCollection.find(:all,:params => {:page=> page})
      collectionEdits.each do |collectionEdit|
        collectionEdit.disjunctive = 'true'
        collectionEdit.save
      end
      count = count - 50
      page = page + 1
    end