Thursday, April 3

ActiveRecord - CRUD operations - 2

We learn t how to create rows in the database. Moving next in CRUD, it is Reading data from db tables. Reading data involves/requires set of constraints/conditions. Something like, details of specific user, product pricing range, sorting order, matching criteria... and the list goes on. To go ahead with these operations ActiveRecord provides the following handy methods, parameter symbols to you:

find
find_by_xyz
find_by_sql

:first :all :conditions :include :order :limit :select :joins :offset :readonly :lock
etc...

Getting into details, previously we created few rows about user into users table. Now we use this find to read/retrieve the data. Little about "find", it is counterpart for "select * from users" in SQL. The syntax is very plain and simple to pick up.
Say, now I want to read/retrieve the data of all users.

User.find(:all)
so the find method connects to users table (through User class of model) and through parameter "all" it fetches info of all the users a simple array. If we use parameter :first, then only first record would be fetched.
User.find(:first)
say now I want to introduce some constraints. :conditions is the parameter to be used.
Like, I want user with a specific name
User.find(:first,
:conditions => "name='sumanth'" )

but in case the name to be matched comes dynamically through params, then there would be slight change in the above syntax. Like this,
User.find(:first,
:conditions => "name=?,params[:name] ")

or

User.find(:first,
:conditions => "name= '#{
params[:name] }'")


if you want more than one parameter to be checked/matched in the conditions then we can separate each with 'and'.

User.find(:first,
:conditions => ["name=? and email=?",params[:name] ,params[:email]])
thus we can play around with more options/parameter that "find" accommodates. Don't forget to separate each options with "," as I had used it after :first and before :conditions options.

No comments: