问题
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 vendor, something like
Vendor.all.pluck(prices.order("data ASC").first.data)
How can I go about extracting the lowest price data element for each vendor in this scenario? Thank you in advance for the help.
回答1:
For each vendor, use minimum(:data) on its associated prices:
Vendor.includes(:prices).map { |v| v.prices.minimum(:data) }
回答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}
回答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)
来源:https://stackoverflow.com/questions/18131055/pluck-last-value-of-an-association-in-rails