ActiveRecord
On this page - Minimal ActiveRecord - Attributes - Intercept Attributes - Alias Attributes - Delegate Attributes - Add Attributes - Update Attributes - Reflection on Attributes - Accessing attributes before they have been typecast - Protecting Attributes - Manipulate Counters - Toggle Booleans - new versus create - save vs save! and create vs. create! - Understanding save cascades in associations - Find - Dynamic Attribute-Based Find - Callbacks - Associations - One-to-One: belongs_to and has_one - One-to-Many: has_many - Many-to-Many: has_many :through and habtm - has_many :through, :source - has_many :through, :uniq - Association Callbacks - Polymorphic Associations - Aggregations - Validations - Acts as List - Acts as Tree - Acts as Nested Set - Single Table Inheritance - Scoping :with_scope See also: - the Wikipedia Active record pattern entry - the Official ActiveRecord Overview - the ActiveRecord::Base API docs - the Caboose Edge ActiveRecord API docs
Minimal ActiveRecord
The simplest possible ActiveRecord model has virtually no application specific code, yet has a great deal of functionality. Here's a minimal ActiveRecord model:
And let's say that the monkeys table (see Database Conventions) in our database has the following structure:
+-----------------------------------------------+ | TABLE monkeys | +--------------+---------------+----------------+ | Field | Type | Other | +--------------+---------------+----------------+ | id | integer | primary key | | name | varchar(50) | | | age | integer | | | bionic_arm | boolean | | | species | varchar(50) | | +--------------+---------------+----------------+
With this simple configuration we have read and write access to all our model's attributes and we can search our existing records in a variety of ways:
Attributes
ActiveRecord infers model attributes from the database. Each attribute gets a getter, setter, and query method.
There are several magic attribute names that you should not inadvertently use - here is a list, more details can be found on the Database Conventions page.
created_at updated_on lock_version
created_on updated_at type
id #{table_name}_count position
parent_id lft rgt
Intercept Default Attribute Accessors
If you wish to manipulate an attribute before or after it is saved in the model object (and perhaps ultimately the database), you may override the default accessors and use read_attribute and write_attribute to actually change the stored attribute value. For example:
Alias Attributes
See also: - Ruby alias method alternative
New in Rails 1.2! Now you may use the alias_attribute method to alias an attribute name and automagically acquire getter, setter, and query methods just like a real attribute.
Delegate Attributes
See Also: - Mailing list post on this topic
The delegate method allows you to add contained objects methods to your current objects methods. So for example (taken from the mailing list post linked above), the Mephisto blogging software pulls the year, month, and day methods up from the :published_at DateTime object into the Content object:
Add Attributes
You may also add attributes to your model. Perhaps you want a synonym for an existing attribute or alternate access to an existing attribute:
Update Attributes
You may update attributes individually or in mass as a hash using either the attributes=, update_attribute, or update_attributes methods. Both of the update_* methods instantly save the record (assuming validations pass). You should be aware that calling update_* on an unsaved model will save it! New values assigned via the attributes= method must be explicitly saved.
Reflection on Attributes
The attribute_names method returns all of the attribute names for an ActiveRecord object and the attribute_present? method indicates if an attribute has a non-nil value or (if a String) is not empty. You may also use has_attribute? to query if a model has a particular attribute.
Accessing attributes before they have been typecast
Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. That can be done by using the {attribute}_before_type_cast accessors that all attributes have.
This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn’t what you want.
Protecting attributes
See also: - Securing your Rails application - a strong case for attr_accessible
Sometimes you just don't want model attributes to be easily modifiable (think passwords, account balances, and bionic arms!). You can protect your critical attributes with attr_protected or explicitly note only those attributes that are accessible with attr_accessible.
Increment and Decrement Counters
- for documentation on the counter_cache see the Cached Counters on the Database Conventions page
There are several methods available to simplify the management of counter attributes
There are also the increment_counter and decrement_counter class methods - both of these methods instantly update the value in the database.
Toggle Boolean Attributes
Boolean attributes may be flipped with the toggle and toggle! methods (the "!" method saves to the database).
Model.new versus Model.create
Both new and create will return a new model object but create also saves the record to the database (assuming it passes validations), so: