ActiveRecord find and only return selected columns

timpone picture timpone · Oct 27, 2011 · Viewed 136.3k times · Source

edit 2

If you stumble across this, check both answers as I'd now use pluck for this


I have a fairly large custom dataset that I'd like to return to be echoe'd out as json. One part is:

l=Location.find(row.id)
tmp[row.id]=l

but I'd like to do something like:

l=Location.find(row.id).select("name, website, city")
tmp[row.id]=l

but this doesn't seem to be working. How would I get this to work?

thx

edit 1
alternatively, is there a way that I can pass an array of only the attributes I want included?

Answer

prasad.surase picture prasad.surase · Oct 11, 2012

pluck(column_name)

This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.

Examples:

Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns