Ruby on Rails: Is there a method to retrieve an array of data from the database without Rails needing to instantiate anything?
I have a model that I'开发者_如何学Cm 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?
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.
In Rails 3.x you could use pluck
to return an Array of the desired attributes straight off of the DB without instantiating an object.
titles = Book.where(:foo => 'bar').pluck(:title)
#SELECT TITLE FROM BOOKS WHERE FOO = 'BAR'
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.
You can use gem pluck_to_hash
https://github.com/girishso/pluck_to_hash
It works similar to pluck
but returns array of Hashes
Post.limit(2).pluck_to_hash(:id, :title)
#
# [{:id=>213, :title=>"foo"}, {:id=>214, :title=>"bar"}]
#
精彩评论