back to

The Rails 4 Way

ARCHIVED

Archived: This project has been archived. Cards can no longer be completed.

Working with Active Record

Alejo
Alejo completed this card.
Active Record is the framework included with Rails for creating database-bound model classes.

The Active Record pattern, identified by Martin Fowler, maps one model class to one database table, and one instance of that class to each row of that database table.

By convention, Rails maps Active Record classes to database tables with pluralized names (User class, users_table), and it also expects an id column to use as primary key.

Default attribute values

You can set default values for your attributes at the model level in the following way:

Default attribute values


Serialized attributes

One example of using serialization would be to store user preferences in a hash, as opposed to creating a preferences table related to the user.

ActiveRecord::Store

The store declaration uses serialize to declare a single-column key/value store.
store declaration.png 30.16 KB



store.png 74.25 KB


Preventing SQL Injection attacks

To prevent SQL Injection attacks always parameterize your query. This means, always declare variables as question marks "?" in your SQL queries, never interpolate supplied values into a SQL fragment.

Convenience Updaters

Rails has increment, decrement, and toggle, which can be called with a bang which will invoke update_attribute.

Database Locking

Database locking is useful if in your application, there's a object that could be updated by two people at the same time. The way to solve this is by adding: 
Database Locking


"Simply adding that lock_version column changes Active Record’s behavior. Now if the same record is loaded as two different model instances and saved differently, the first instance will win the update, and the second one will cause an ActiveRecord::StaleObjectError to be raised."