Rails Find an entry in ActiveRecord :: Relation Object without querying the database again

I want to find a specific record in an ActiveRecord::Relation object so that I can capture this record attribute.

Below is shown, but the problem is that it again deletes the database using this find_by . It should not be. There should be a way for the rails to find this object in an ActiveRecord::Relation object, rather than querying the database again.

 #returns an ActiveRecord::Relation object @blogs = Blog.all # Search for the blog within that ActiveRecord::Relation object, NOT the database @blogs.find_by(id: 1).title #do this statement but don't hit the database again 
+13
ruby ruby-on-rails activerecord
source share
4 answers

After loading realtion, you can use the usual array methods. find is really a very interesting method here - if a block is given, it will be delegated to the target of the relation:

 @blogs.find {|b| b.id == 1} 
+15
source share

When you call find_by , it gets into the database.

A relationship object is used to lazily load db results.

Once they are loaded to call all , you can search the resulting array.

If you want to look at the results already recorded in your ruby โ€‹โ€‹process, you have to look into the array using find or detect (which do the same). I usually use detect , so it is clear that it does not get into the database:

 @blogs.detect { |b| b.id == 1 } 

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-detect

+12
source share

You can expand a specific association as follows:

 class User < AR has_many :roles do def find_for(params) find { |record| params.all? { |key, val| record[key] == val } } end end end User.first.roles.find_for(foo: 'bar', baz: 'word') # => return instance of Role if its #foo equal 'bar' and its #baz equal 'word' 
0
source share

You can always use the where clause. For example,

 @blogs.where(id: 1).first.reload 

Get (and reload from the database) an @blog instance with identifier 1. And keep in mind that this request will be fast, efficient and safe (in case you want to add params[:id] instead of a hard-coded ID.

-2
source share

All Articles