Rails where or select for query chaining

痞子三分冷 提交于 2019-12-13 16:25:27

问题


So when querying a database, I know it's much better to use where on the initial query like so:

pending = Request.where("status = ?", "Pending").order! 'created_at DESC'

However, if I need to further filter this information, I can do it with either where or select:

high_p = pending.where("priority = ?", "High Priority")
normal_p = pending.where("priority = ?", "Priority")

Or

high_p = pending.select{|x| x.priority == "High Priority"}
normal_p = pending.select{|x| x.priority == "Priority"}

My question is which of these is better from a performance standpoint? Should we always use where? Or does select have a use case when the whole database isn't being searched?


回答1:


where is much better from a performance standpoint. where modifies the SQL so that the DB does the "heavy lifting" of identifying records to retrieve.

select retrieves all records that meet the initial where condition, converts them into an array, and uses `Array#select' so the selection is happening at the rails end and you've retrieved more records from the db than you needed and done more processing than is necessary.

Select does have an advantage in that you can select based on model methods that may not be simply extracted from table columns. For example you may have a model method #bad_credit? which is determined by, say, a credit limit, age if outstanding invoices, and type of account.



来源:https://stackoverflow.com/questions/42448821/rails-where-or-select-for-query-chaining

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