I have an array with products, I need to display only 1 product, with the largest number in available_amount. How can i do this?
How do I iterate to display products with parameters:
- @part.wh_ps.sort_by(&:available_amount).each do |whp|
product number1: available_amount: 2;
product number2: available_amount: 5;
>Solution :
If those objects are mapped from the database being the result of a query and you already have them in memory, then you could use Enumerable#max_by:
@part.wh_ps.max_by(&:available_amount)
It should return the object within that array with the biggest available_amount if any.
If you need the one with the lowest available_amount, then Enumerable#min_by, and if you need both Enumerable#minmax_by.
However if that’s not the case and you’re hitting the database again, you could consider making the exact query using SQL (ActiveRecord) asking for the row with the biggest value for the given column.