In this conclusion to a three-part series on the Rails framework's Active Record, you'll learn how to use dynamic finders, update and delete records, and more. This article is excerpted from chapter four of the book Beginning Rails: From Novice to Professional, written by Jeffrey Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Updating and Deleting with the Active Record (Page 1 of 4 )
Finding with Conditions
While finding a record by its primary key is useful, it requires that you know theidto begin with, which isn’t always the case. Sometimes you want to find records based on other criteria. This is where conditions come in to play. Conditions correspond to the SQLWHERE clause. If you want to find a record by its title, you pass a hash of options tofindwith a key of:conditionsand a value that contains either a hash of conditions or a SQL fragment.
Here, we’ll use a hash of conditions to indicate we want the first event with the title ofRailsConf.
Because we usedfind(:first), we’ll get only one record (the first one in the result set, even if there is more than one result). If we instead usefind(:all), we’ll get back a collection, even if the collection has only one item in it.
Notice the square brackets and remember that they indicate an array. More often than not, when you’re doing afind(:all)operation, you’re expecting more than one record in return. Butfind(:all)will always produce an array, even if that array is empty.
It doesn’t get any easier than dynamic finders. We call these finders dynamic because they use Ruby’smethod_missingfunctionality to automatically create methods that don’t exist until runtime. Using dynamic finders, you can include the attribute you’re looking for directly in the method name. This will make more sense when you see it in action.