skip to Main Content

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


  1. Chosen as BEST ANSWER

    I tried something myself. I introduced:

    @productIds = Product.pluck(:product_id)
    

    Then a new loop:

     @products.delete_if do |product|
      if product.id.in?(@productIds)
        true 
      end
    end
    

    Seems to do this trick for now.


  2. Yes!

    ShopifyAPI::Product.find(:all) will fetch all the products in the store.
    so you need to add the condition into your controller.

    Option1

    @myproducts = Product.where.not(id: nil).select(:id, :title)
    @products = ShopifyAPI::Product.find(:all)
    myproducts_titles = @myproducts.map(&:title)
    @products = @products.reject do |product|
      myproducts_titles.include? product.title
    end
    

    Option2

    @myproducts = Product.where.not(id: nil).select(:id, :title)
    myproducts_titles = myproducts.map(&:title)
    @products = ShopifyAPI::Product.find(:all)
    products_titles = @products.map(&:title)
    newproducts_titles = products_titles - myproducts_titles
    @products = @products.select do |product|
      newproducts_titles.include? product.title
    end
    

    I’m not sure whether which options are much faster

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search