My app imports products from a Shopify store. It needs to cater for products that have previously been imported in to my apps database and also show any new products that have been added to the Shopify store since the last import.
My view is:
# All new products in Shopify
<% @products.each do |product| %>
<tr>
<td><%= product.id %></td>
<td><%= product.title %></td>
</tr>
<% end %>
# All existing products in my app
<% @myproducts.each do |myproduct| %>
<tr>
<td><%= myproduct.id %></td>
<td><%= myproduct.title %></td>
</tr>
<% end %>
The part of ProductsController
controller responsible grabbing these is:
@products = ShopifyAPI::Product.find(:all)
@myproducts = Product.where.not(id: nil)
The issue is that the first each loop displays all products from the Shopify store, including those products already in @myproduct.each do
loop. So we end up having a lot of double-ups.
I need @products.each
loop to only display products where product.id
does not already exist as myproduct.id
.
Should I be using an if statement in my view or some conditions in @products = ShopifyAPI::Product.find(:all)
?
2
Answers
I tried something myself. I introduced:
Then a new loop:
Seems to do this trick for now.
Yes!
ShopifyAPI::Product.find(:all)
will fetch all the products in the store.so you need to add the condition into your controller.
Option1
Option2
I’m not sure whether which options are much faster