Pluck - a Little Tool to Reduce Database Load

Very often in rails we use something like this

project_ids = current_user.projects.map(&:id)

which gives us an array of project_ids as a result. Behind the scene it is something like

projects = current_user.projects

SELECT `projects`.* FROM `projects` WHERE `projects`.`user_id` = 1

project_ids = projects.map {|p| p.id }

Which means, It fetches all the projects for a user and then loop over all projects to extract the id. Instead we can simply use

project_ids = current_user.projects.pluck(:id)

SELECT `projects`.`id` FROM `projects` WHERE `projects`.`user_id` = 1

Which gives the same output with less load on database. Simple and precise. More.

Update

Pluck can be used to fetch two or more columns now like

users_array = User.pluck(:id, :email)

Comments