Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Find a Record Within ActiveRecord::Relation Object without querying database again

I want to find a specific record within an ActiveRecord::Relation object so I can grab that record's attribute.

The below works, but the problem is that it is hitting the database again with that find_by statement. It shouldn't have to. There should be a way for rails to find that object within the ActiveRecord::Relation object as opposed to having to query 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 
like image 560
Neil Avatar asked Jul 08 '15 14:07

Neil


People also ask

What is the difference between find and Find_by in rails?

The additional difference between find() and find_by() is that find could only be used to search by primary key (usually the 'id') while the find_by() requires and searches by attribute (either passed as hash like Employee. find_by(name: 'Mike') or using the Employee.

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

What is an ActiveRecord object?

In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic as part of the object will educate users of that object on how to write to and read from the database.


1 Answers

Once the relation has been loaded, you can use regular array methods. find is actually a very interesting method here - if block is specified, it will be delegated to the relation target:

@blogs.find {|b| b.id == 1} 
like image 101
BroiSatse Avatar answered Sep 19 '22 23:09

BroiSatse