Reputation: 660
I am trying to download products from a Magento store into my Rails database using the "magento-rb" library located here: https://github.com/joelvh/magento-rb
I've tried the following code:
xml_api = Magento::XmlApi.new "http://website.com/api/xmlrpc/", "myusername", "mypassword", :debug => true
products = xml_api.call("catalog_product.list")
products.each do |p|
@exists = Product.where("sku = ?",p["sku"])
if @exists
@product = Product.find_by_sku(p["sku"])
else
@product = Product.new
end
@product.sku = p["sku"]
@product.name = p["name"]
@product.mage_product_id = p["product_id"]
@product.save
end
Unfortunately I am getting this error:
NoMethodError in Admin::ProductsController#test
undefined method `sku=' for nil:NilClass
I should note that I have confirmed that "sku" is indeed an attribute to the Product model, and I have also tried resetting the server. Any ideas?
Upvotes: 0
Views: 178
Reputation: 230
The way you wrote the code, @exists
is always true
so even when the sku doesn't exist, the where() method will return an empty array which evaluates to true
in ruby.
The only values that evaluate to false in ruby are false
and nil
.
That's why when you use Product.find_by_sku
, it returns nil
because the sku doesn't exist and THAT is why you're getting the error undefined method sku= for nil:NilClass
.
It's like you're writing nil.sku = p['sku']
which won't work.
To check the existence of a record in the database, it's better to use the 'exists?' method:
if Product.exists?(["sku = ?",p["sku"]])
# product exists
else
# product doesn't exist
end
You can actually skip the extra record checking and only use the find_by_sku method to both check for existence and get the record if it exists at the same time. The following code does the same thing, but it's more "ruby-like":
@product = Product.find_by_sku(p['sku'])
@product = Product.new unless @product
@product.sku = p['sku'] # this is unnecessary
@product.name = p['name']
@product.mage_product_id = p['product_id']
@product.save
Upvotes: 1