Reading and Deleting
Explore how to use Active Record in Rails for reading and deleting database rows safely. Understand querying with conditions, parameterization to prevent SQL injection, working with subsets, ordering, grouping, and deleting data properly during application development.
Reading existing rows
Reading from a database involves first specifying which particular rows of data we are interested in. We’ll give Active Record some kind of criteria, and it will return objects containing data from the row(s) matching the criteria.
The most direct way of finding a row in a table is by specifying its primary key. Every model class supports the find() method, which takes one or more primary key values. If given just one primary key, it returns an object containing data for the corresponding row or throws an ActiveRecord::RecordNotFound exception. If given multiple primary key values, find() returns an array of the corresponding objects. Note that in this case, a RecordNotFound exception is raised if any of the IDs cannot be found. So, if the method returns without raising an error, the length of the resulting array will be equal to the number of IDs passed as parameters.
Often, though, we need to read in rows based on criteria other than their primary key value. Active Record provides additional methods enabling us to express more complex queries.
SQL and Active Record
To illustrate how Active Record works with SQL, pass a string to the where() method call corresponding to a SQL where clause. For example, to return a list of all orders for Dave with a payment type of po, we could use this:
pos = Order.where("name = 'Dave' and pay_type = 'po'")
The result will be an ActiveRecord::Relation object ...