07 August 2012

Rails: ActiveRecord and ActiveRelation

ActiveRecord
"active record" is a way of writing software (a software design pattern. )
"ActiveRecord" is a rails implementation of  active record.

Basically, it retrieves and manipulates db data as objects and NOT just as static rows.
ActiveRecords lets the objects
  • understand the structure and 
  • they know how to interact with it.  
  • They contain data but also have the ability to create, read, update and delete rows.

Examples of ActiveRecord:
To do a SQL Insert:
user = User.new
user.first_name = "Brian" 
user.save

To do a SQL Update:
user.last_name = "Warner"
user.save

To do a SQL Delete:
user.delete

ActiveRelation
This is new in Rails 3
This simplifies the generation of complex db queries.
Also, it handles the timing of queries, so these queries execute when needed.

Example of ActiveRelation:
Instead of the SQL:
select users.*, articles.*
from users
left join articles on (users.id = articles.author_id)
where users.first_name = 'Brian'
order by last_name ASC Limit 5;

it would be written like this:
users = User.where(:first_name => "Brian")
users = users.order("last_name ASC").limit(5)
users = users.include(:articles_authored)

So it shrinks down the SQL queries to some simple Ruby lines.

No comments:

Post a Comment