Saturday, December 25, 2010

SQL equivalence of Ruby on Rails Model syntax

In Ruby on Rails, Model classes are handled through the Active Record. This means that for each table in database, there exists a corresponding class in the application. This class then has all functions needed to create, find, update, and delete rows in the database table. Usually, all the programmer needs to do is to subclass the ActiveRecord::Base class, and the program will automatically figure out which RDBMS table to use and what columns the table has.
For example, if there is a class Post, the following code:
a = Post.new
a.subject = "Example message"
a.body = "This is an example message."

is conceptually equivalent to the following SQL command:
INSERT INTO posts (subject, body)
VALUES ('Example message', 'This is an example message.');

and the following code:
b = Post.find(:all, :conditions => ['score > 80'])

is conceptually equivalent to the following SQL command:
SELECT * FROM posts WHERE score > 80;


  1. Thanks for your clear explanation. But i have some doubt, I want to select the all record without lock in sql server,

    For example

    SELECT * FROM employees WITH(NOLOCK)

    How can i write in model?

  2. may be this helps you http://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html#method-i-lock-21


fuzionpro Headline