1

Been stuck on this for some time as I have tried things like .uniq and .map but my issue is as follows:

I have @products which make up all the products in the inventory for my store.

@products also have variations through size, color, etc where I can control stock, etc.

the unique part of @products is the product.sku

Ideally I need to display the product just once based on sku.

Any help would be appreciated.

UPDATE: I tried the answer below as such and it did not work:

@products = Shoppe::Product.where(product_category_id: 1)
puts "####################################################"
puts @products.count
puts "####################################################"
@products = @products.uniq { |product| product.sku }
puts "####################################################"
puts @products.count
puts "####################################################"

The counts return the same

sump
  • 506
  • 2
  • 15

2 Answers2

1

You can return unique items based on their attributes using Array#uniq with a block:

@products.uniq {|product| product.sku}
Aeyrix
  • 168
  • 7
1

You can use ActiveRecord distinct method, which is a wrapper to SQL DISTINCT syntax.

Shoppe::Product.select(:sku).distinct
# Note that this would only bring the sku column

Or you can can specify a SQL query inside the select to a more custom result:

Shoppe::Product.select("DISTINCT ON (products.sku) products.*").where(product_category_id: 1)
# This one however would bring everything from products table
MurifoX
  • 14,991
  • 3
  • 36
  • 60
  • I tried this but it seems you missed a closing quotation. As such I put it after the products.* and received a SQL Error: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "products" LINE 1: SELECT DISTINCT ON (@products.sku) @products.* FROM "shoppe – sump Jul 27 '15 at 19:09
  • To what table does `Shoppe::Product` maps to? It isn't `products`? Change it to the name of your table and you are good to go. – MurifoX Jul 27 '15 at 19:14
  • doh! i'm an idiot. i'll update the table names and try that. – sump Jul 27 '15 at 19:23
  • thank you so much ! although it gave me 1 drawback. in my pagination it still thinks all those products are still there. i'll try playing around with that unless you have any ideas for there too ! :) – sump Jul 27 '15 at 19:25
  • To be honest, i didn't understand your pagination problem. – MurifoX Jul 27 '15 at 19:29
  • It still shows the amount of pages as per the total amount of products but only displays based on sku.... if that makes sense? so for example you have 10 products and 5 are uniq and you paginate 5 per page you should only receive 1 page but it shows 2 pages where page 2 is blank. – sump Jul 27 '15 at 19:30
  • Oh that's odd. Maybe it is a bug. I found something related to it, give it a read (http://stackoverflow.com/a/10740732/1023609). – MurifoX Jul 27 '15 at 19:34