ActiveRecord find and only return selected columns

Ruby on-RailsRuby on-Rails-3Rails Activerecord

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontimponeView Question on Stackoverflow
Solution 1 - Ruby on-Railsprasad.suraseView Answer on Stackoverflow
Solution 2 - Ruby on-RailsjeffluntView Answer on Stackoverflow
Solution 3 - Ruby on-RailstkhuynhView Answer on Stackoverflow