CSC/ECE 517 Fall 2012/ch1b 1w63 dv

From Expertiza_Wiki
Jump to navigation Jump to search

ACTIVE RECORD

1 Introduction.

The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert, Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.

ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern.

The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.

2 Naming

The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.

2.1 Reserved names and Attributes:

Certain names are reserved and should not be used (even in the model as attributes) for example:

lock_version type - This is only used when you have single table inheritance and must contain a class name id - Reserved for primary keys table_name_count - Reserved for counter cache position - Reserved for acts_as_list parent_id - Reserved for acts_as_tree lft - Reserved for acts_as_nested_set rgt - Reserved for acts_as_nested_set quote - Method in ActiveRecord::Base which is used to quote SQL template


2.2 Class Naming

ActiveRecord classes are named in singular form. e.g User

2.3 Table Naming

Tables for ActiveRecord objects are named in plural form by default. e.g. Users This naming convention can be circumvented by using below:

a) Set use_pluralization In the environment.rb file we can specify ActiveRecord::Base.use_pluralization = false.

This will disable pluralization for all ActiveRecord objects.

b.) Use set_table_name You can call set_table_name to specify a custom table name for a particular model. For example:

 class User < ActiveRecord::Base
   set_table_name 'user'
 end

3 CRUD

   3.1 Create
           <Use relevant code snippets>
   3.2 Read
  3.3 Update
  3.4 Delete