0

I'm dealing with a shopping cart, which has many products in it. The products can be sold by multiple different companies. What I'm trying to do is select the companies uniquely so that I can create one order per vendor.

the hack

companies = []
@cart.products.each { |p| companies << p.company }
companies.uniq
#create order for each company

I'm not sure if #pluck is something I should be using here, but I do know that there has got to be a more efficient way of collecting my companies "uniquely". #uniq doesn't seem to be working for me, and neither does @cart.products.pluck(:company)

I have no :company_id in my Bid model, it's a has_many/has_one relationship

gemart
  • 346
  • 1
  • 3
  • 18

1 Answers1

1

pluck is used for retrieving array of values in provided column like: @cart.products.pluck(:company_id) # => [1,2,3]

For collecting companies you can do companies = @cart.products.collect(&:company).uniq

Krzysztof
  • 30
  • 3
  • Awesome, this works.. Can you clarify for me what the ampersand does? I've never really known when and when not to include it. – gemart Mar 24 '17 at 14:07
  • Sure thing. It's a shorthand for `@cart.products.collect(&:company.to_proc)`. It's equivalent to `@cart.products.collect {|prod| prod.company}`. This work only for objects that implement or inherit `to_proc` method. There is great explanation here: http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby – Krzysztof Mar 27 '17 at 06:57