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
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.
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/…
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With