如何从 Shopify with Ruby 中删除/替换智能收集规则



我创建了一个脚本来向 Shopify 智能集合添加条件规则,但在此之前,我需要它删除所有当前条件,以便新条件是唯一的条件。我遇到了一个问题,在尝试删除它们时会回放一个未定义的错误。

脚本:

@update_collection = ShopifyAPI::SmartCollection.find(411011140)
@a = @update_collection.rules[0].attributes
@a.delete_all
@update_collection.rules << ShopifyAPI::Rule.new(:column => 'tag', :relation => 'equals', :condition => 'test12')
@update_collection.save
puts "#{update_collection.title} Updated"

错误输出:

NoMethodError: undefined method `delete_all' for #<ActiveSupport::HashWithIndifferentAccess:0x007fc2cbafd008>

我尝试单独删除每个属性,这不是我确定的正确方法,它会删除属性而不是整个规则,并在保存时导致错误。

脚本:

@update_collection = ShopifyAPI::SmartCollection.find(411011140)
@a = @update_collection.rules[0].attributes
@a.delete("column")
@a.delete("relation")
@a.delete("condition")
@update_collection.rules << ShopifyAPI::Rule.new(:column => 'tag', :relation => 'equals', :condition => 'test12')
@update_collection.save
puts "#{update_collection.title} Updated"

错误输出:

irb(main):1806:0> @update_collection.save
=> false

错误查找:

IRB(主):1818:0> @update_collection.错误

"rules"=>[#, #"tag", "relation"=>"equals", "condition"=>"test12"}, @prefix_options={}, @persisted=false>]}, @prefix_options={}, @persisted=true, @remote_errors=#, @validation_context=nil, @errors=#>, @messages={:conditions=>["are not valid">

]}, @details={:conditions=>[{:error=>"are not valid"}]}>

我尝试了.destroy并收到以下错误:

脚本:

@update_collection = ShopifyAPI::SmartCollection.find(411011140)
@a = @update_collection.rules[0].attributes
@a.destroy
@update_collection.rules << ShopifyAPI::Rule.new(:column => 'tag', :relation => 'equals', :condition => 'test12')
@update_collection.save
puts "#{update_collection.title} Updated"
NameError: undefined local variable or method `params' for #<ActiveSupport::HashWithIndifferentAccess:0x007fc2cc168280>

我不确定我错过了什么或做错了什么。任何正确方向的点将不胜感激!

Shopify API 文档:https://help.shopify.com/api/reference/smartcollection

我只是想指出,我已经为我们的问题创建了一个创可贴,尽管对于多个集合,这可能不是编写脚本和循环访问有问题的集合的正确方法。对于正在尝试相同事情的未来个人,我已经包含了似乎有效的脚本。

@a = ShopifyAPI::SmartCollection.find(COLLECTIONID)
# The line above finds the collection via ID
@a.rules = nil
# The line above changes all of the rules to a "null" value
@a.save
# After changing the condition rules to null we save
@b = ShopifyAPI::SmartCollection.find(COLLECTIONID)
# We go back into the collection and add a new rule (this will be the only existing rule we have now)
@b.rules << ShopifyAPI::Rule.new(:column => 'tag', :relation => 'equals', :condition => 'YOURTAG')
# The above line will add a new rule
@b.save
# We save it again to add the new rule
# If you'd like to test it you can add "@b.reload" to reload the collection information that currently exists and you should see your older rules removed and the new one in place

最新更新