Pluck Last Value Of An Association In Rails
The model Price has an attribute data, so Price.pluck(:data) results in something like [3.99,4.55,5.44] And Price belongs to Vendor So I want to select the best price for each ven
Solution 1:
For each vendor, use minimum(:data) on its associated prices:
Vendor.includes(:prices).map { |v| v.prices.minimum(:data) }
Solution 2:
Here's another approach which puts more work on the database and less on Ruby. (I'm pretty sure the code in @meagar 's answer will issue a select for each vendor during the map). Which way is better (faster) may depend on how big your tables are…
You could do something like this, which will issue one SQL statement:
Vendor.select('min(prices.data) as min_price').from('vendors').joins('INNER join prices on vendors.id = prices.vendor_id').group('vendors.id')map {|v| v.min_price}
Solution 3:
You don't gain anything from getting the Vendor model involved--everything you need to know about vendor is already in the Price model as vendor_id, right?
So all you need is:
Price.order(:data).group(:vendor_id).pluck(:data)
Post a Comment for "Pluck Last Value Of An Association In Rails"