Ruby on Rails: Is there a way to retrieve an array of data from a database without the Rails needed to instantiate?

I have a model from which I am trying to get an array of data, and I do not need the data that will be created in the Ruby objects. In fact, it just introduces an extra step into my code to go through the objects and create a new array with the data I need.

Example:

class Book #has attribute in database title end 

I would like to create an array that contains all the titles of all the books in the database. What is the best way to do this?

+3
source share
4 answers

ActiveRecord gives you direct access to the current environment database, allowing you to execute SQL queries and return the result to the underlying structures (arrays or hashes). See: http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html

For instance:

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

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

+8
source

In Rails 3.x, you can use pluck to return an array of the required attributes directly from the database without creating an instance of the object.

 titles = Book.where(:foo => 'bar').pluck(:title) #SELECT TITLE FROM BOOKS WHERE FOO = 'BAR' 
+7
source

This is not how Rails works. You could write some middle-sized product or something that goes beyond the scope, but is probably not worth your time. Rails is (or at least the focus) on developer productivity. Just do it like this:

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

As for performance issues (assuming your site is growing), you just start caching this result.

+2
source

You can use gem pluck_to_hash https://github.com/girishso/pluck_to_hash

It works like pluck , but returns an array of hashes

 Post.limit(2).pluck_to_hash(:id, :title) # # [{:id=>213, :title=>"foo"}, {:id=>214, :title=>"bar"}] # 
0
source

Source: https://habr.com/ru/post/1286475/


All Articles