views:

40

answers:

2

I have a model that I'm trying to retrieve an array of data from, and I don't need the data to be instantiated into Ruby objects. In fact, that just introduces an extra step into my code to step through the objects and generate a new array with just the data I need.

Example:

class Book
  #has attribute in database title
end

I would like to generate an array which contains all the titles of all the Books in the database. What's the best way to do it?

+2  A: 

That's not how Rails works. You could write some middle-ware or something that circumvents the framework but it's probably not worth your time. Rails is all about (or at least, has a focus on) developer productivity. Just do it like this:

titles = Book.find( :all ).map( &:title )

As for performance concerns (assuming your site grows) you simply start caching this result.

thenduks
Beerlington
True, also your comment reminded me about an ActiveRecord plugin I came across once called slim-attributes (http://slim-attributes.rubyforge.org/) that does some stuff along these lines.
thenduks
+1  A: 

ActiveRecord gives you a direct hook to the current environment database, allowing you execute SQL statements and returning the result in basic structures (arrays or hashes). See: http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html

For example:

ActiveRecord::Base.connection.select_values("SELECT title FROM books")

Will return an array of book titles (strings). This will not instantiate any ActiveRecord instances and will be more memory efficient for your application.

Jose Fernandez