Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord find and only return selected columns

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?

like image 270
timpone Avatar asked Oct 27 '11 02:10

timpone


3 Answers

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

like image 121
prasad.surase Avatar answered Sep 28 '22 16:09

prasad.surase


In Rails 2

l = Location.find(:id => id, :select => "name, website, city", :limit => 1)

...or...

l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.

In Rails 3 w/ActiveRecord Query Interface

l = Location.where(["id = ?", id]).select("name, website, city").first

Ref: Active Record Query Interface

You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.

like image 22
jefflunt Avatar answered Sep 28 '22 16:09

jefflunt


My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

like image 45
tkhuynh Avatar answered Sep 28 '22 18:09

tkhuynh