Model in Ruby

From Logic Wiki
Jump to: navigation, search


Active Record

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Naming Conventions

When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:

  • Database Table - Plural with underscores separating words (e.g., book_clubs).
  • Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).
Model / Class Table / Schema
Article articles
LineItem line_items
Deer deers
Mice mouse
Person people

Schema Conventions

Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.

  • Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id, order_id). These are the fields that Active Record will look for when you create associations between your models.
  • Primary keys - By default, Active Record will use an integer column named id as the table's primary key. When using Active Record Migrations to create your tables, this column will be automatically created.

There are also some optional column names that will add additional features to Active Record instances:

  • created_at - Automatically gets set to the current date and time when the record is first created.
  • updated_at - Automatically gets set to the current date and time whenever the record is updated.
  • lock_version - Adds optimistic locking to a model.
  • type - Specifies that the model uses Single Table Inheritance.
  • (association_name)_type - Stores the type for polymorphic associations.
  • (table_name)_count - Used to cache the number of belonging objects on associations. For example, a comments_count column in a Articles class that has many instances of Comment will cache the number of existent comments for each article.

Creating Active Record Models

It is very easy to create Active Record models. All you have to do is to subclass the ActiveRecord::Base class and you're good to go:

class Product < ActiveRecord::Base
end

his will create a Product model, mapped to a products table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose that the products table was created using an SQL sentence like:

CREATE TABLE products (
   id int(11) NOT NULL auto_increment,
   name varchar(255),
   PRIMARY KEY  (id)
);

Following the table schema above, you would be able to write code like the following:

p = Product.new
p.name = "Some Book"
puts p.name # "Some Book"

Overriding the Naming Conventions

What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.

You can use the ActiveRecord::Base.table_name= method to specify the table name that should be used:

class Product < ActiveRecord::Base
  self.table_name = "PRODUCT"
end

If you do so, you will have to define manually the class name that is hosting the fixtures (class_name.yml) using the set_fixture_class method in your test definition:

class FunnyJoke < ActiveSupport::TestCase
  set_fixture_class funny_jokes: Joke
  fixtures :funny_jokes
  ...
end

It's also possible to override the column that should be used as the table's primary key using the ActiveRecord::Base.primary_key= method:

class Product < ActiveRecord::Base
  self.primary_key = "product_id"
end

CRUD: Reading and Writing Data

Create

Active Record objects can be created from a hash, a block or have their attributes manually set after creation. The new method will return a new object while create will return the object and save it to the database.

For example, given a model User with attributes of name and occupation, the create method call will create and save a new record into the database:

user = User.create(name: "David", occupation: "Code Artist")

Using the new method, an object can be instantiated without being saved:

user = User.new
user.name = "David"
user.occupation = "Code Artist"

A call to user.save will commit the record to the database.

Finally, if a block is provided, both create and new will yield the new object to that block for initialization:

user = User.new do |u|
  u.name = "David"
  u.occupation = "Code Artist"
end

Read

Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.

# return a collection with all users
users = User.all
# return the first user
user = User.first
# return the first user named David
david = User.find_by(name: 'David')
 find all users named David who are Code Artists and sort by created_at in reverse chronological order
users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')

Update

Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.

user = User.find_by(name: 'David')
user.name = 'Dave'
user.save

A shorthand for this is to use a hash mapping attribute names to the desired value, like so:

user = User.find_by(name: 'David')
user.update(name: 'Dave')

This is most useful when updating several attributes at once. If, on the other hand, you'd like to update several records in bulk, you may find the update_all class method useful:

User.update_all "max_login_attempts = 3, must_change_password = 'true'"

Delete

Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.

user = User.find_by(name: 'David')
user.destroy

Validations

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more.

Validation in Ruby is a very important issue to consider when persisting to the database, so the methods save and update take it into account when running: they return false when validation fails and they didn't actually perform any operation on the database. All of these have a bang counterpart (that is, save! and update!), which are stricter in that they raise the exception ActiveRecord::RecordInvalid if validation fails. A quick example to illustrate:

class User < ActiveRecord::Base
  validates :name, presence: true
end
 
user = User.new
user.save  # => false
user.save! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

Callbacks

Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on

Migrations

Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record supports using rake. Here's a migration that creates a table:

rails generate migration create_articles
class CreatePublications < ActiveRecord::Migration
  def change
    create_table :publications do |t|
      t.string :title
      t.text :description
      t.references :publication_type
      t.integer :publisher_id
      t.string :publisher_type
      t.boolean :single_issue
 
      t.timestamps null: false
    end
    add_index :publications, :publication_type_id
  end
end

Rails keeps track of which files have been committed to the database and provides rollback features. To actually create the table, you'd run rake db:migrate and to roll it back, rake db:rollback.

Note that the above code is database-agnostic: it will run in MySQL, PostgreSQL, Oracle and others

To run the migration file and create the articles table:

rake db:migrate

OR

bundle exec rake db:migrate

To rollback a migration (undo the last migration):

rake db:rollback

To add a column (example: created_at column) to the articles table:

rails generate migration add_created_at_to_articles

Then within the def change method in the migration file:

 add_column :articles, :created_at, :datetime

To add a different column (example: name) to a users table:

rails generate migration add_name_to_users

Then within the def change method in the migration file:

add_column :users, :name, :string

In the above two adding column methods, the first argument is the name of the table, second is the attribute name and third is the type To create a model file for Article:

  • In the app/models folder create a file called article.rb
  • Fill it in with the following ->
class Article < ActiveRecord::Base
end

To start the rails console:

rails console

To test connection to the articles table:

Article.all # classname.all will list all the articles in the articles table

Then simply type in Article (classname) to view the attributes

To create a new article with attributes title and description:

article = Article.new(title: "This is a test title", description: "This is a test description")
article.save

OR

article = Article.new
article.title = "This is a test title"
article.description = "This is a test description"
article.save

Another method to do the same:

article = Article.create(title: "This is a test title", description: "This is a test description") # This will hit the table right away without needing the article.save line

To find an article with id 2 and edit it's title:

article = Article.find(2) # Here assumption is article with id of 2 was being looked for
article.title = "This is an edited title"
article.save

To delete an article, example with id 5:

article = Article.find(5)
article.destroy

To add validations presence and length validations to article model for title and description:

class Article < ActiveRecord::Base
  validates :title, presence: true, length: {minimum: 3, maximum: 50}
  validates :description, presence: true, length: {minimum: 10, maximum: 300}
end

To find errors in article object while saving (if it's rolled back):

article.errors.any?
article.errors.full_messages