Pluck last value of an association in rails

房东的猫 提交于 2019-12-11 03:53:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!