Ruby on Rails: Is there a method to retrieve an array of data from the database without Rails needing to instantiate anything?
activerecord, ruby-on-rails
Solution
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.
Problem
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?