Vous êtes sur la page 1sur 1

A Quick Reference on Rails Active-Record CRUD Operations

By Monica Chaturvedi<immcse@gmail.com>

Dynamic Attribute Based Finders: AR Constructors: CRUD-Read- find(*args)


Append attribute to find_by_/find_all_by_ An AR object can be created as follows: Retrieves objects from database by converting the specified criteria into SQL
 Find by single attribute:  Hash: Supplying constructor parameters in a statements. Then it takes the results returned from the database and instantiates
User.find_by_email(“a@b.c”) hash: them as ActiveRecord objects.
 Find by several attributes: user = User.new(:name => "David", :occupation => Syntax: Person.find(primary_key_value,Options)
User.find_by_email_and_password(“a@b.c”, "Artist")  find(id): returns first record matching the id
“pass”,Options) #or isn’t allowed!  Block: Using blocks to initialize: Ex: Member.find_by_id (1), Member.find (1,5,9), Member.find ([1,5,9]). #Exception
 Find or Initialize: user = User.new do |u| RecordNotFound unless record exists.
If record exists, returns it. Else returns a u.name = "David"  find(:first, Options): returns first record matching the Options.
new record without saving it first. end Ex: Member.find(:first) #returns nil unless record exists
User.find_or_initialize_by_email("a@b.c")  Simple:  find(:all, Options): returns all the records matching the Options.
 Find or Create: user = User.new Ex: Member.find(:all) #return an empty array unless members exist.
Creates a new record unless it exists. user.name = "Manni"
Options Hash:
User.find_or_create_by_email("a@b.c") Specifies additional parameters as hash object. Following are the valid options for find:
CRUD-Update  :conditions: Specify conditions to put in WHERE clause.
Conditions:  Increment_counter(attribute,id): Ex: Post.find(:conditions=>{:isVisible= >1})=select * from Posts where isVisible=1
To represent the WHERE part of sql query. Increments the specified attribute by 1  :order: Specify SQL order by criteria.
 String: conditions can be specified in a string. Ex: Post.increment_counter(:votes, 5) #increments the Ex: Post.find(:all,:order =>”colmn desc”)=select * from Post order by colmn desc
:conditions => "email = '#{email}'" #unsafe col “votes” for postId 5
 :group: An attribute name by which the result should be grouped.
 Array:  decrement_counter(attribute,id):
Ex: Post.find(:all,:group=>”member_id”=select * from Post group by member_id
:conditions => [ "email = ? AND password = ?", Decrements the specified attribute by 1
 :limit: Limits the no. of rows to be returned.
email, password ] " #safe & sanitized Ex: Post. decrement_counter(:votes, 5) # #decrement
Ex: Post.find(:all,limit=>10)|= select * from Post Limit 10
 Arrays with symbols: the col “votes” for postId 5
 save(): If new record: Saves else: updates  :offset: An integer determining the offset from where the rows should be fetched. Ex:
:conditions=>[array, {Hash_of _symbols}] Post.find(:offset=>5) #skip rows 0 through 4.
 save!(): Raises a RecordNotSaved exception if
:conditions => ["id = :id OR email = :email",{ :id  :select: Specify list of columns to retrieve.
unable to save.
=> 3, :email => "a@b.c"}]
 toggle(attribute): Toggles the attribute’s value Ex: Post.find(:all, :select => "email,id ")=select email,id form posts
 Hash:
between true and false.  :include: Names associations that should be loaded alongside using LEFT OUTER JOINs. For ex,
:conditions => { :email => email, :password =>  toggle!(attribute): Toggles the attribute and saves it loading members along with posts saves a roundtrip in each loop.
password } #safe & sanitized; #will generate to Db.
AND in sql. Ex: Post.find(:all, :include=>[:member]) #loads member details along with post details
 update_attribute(name, value): updates a single
 Specifying Range inside hash:  :from: Table or View name to select from.
attribute and saves the record
:conditions => { :age => a..b }) #inclusive  update_attributes(attribute_hash) Ex: Post.find(:all,:from=>”MemberPosts”) #select * from MemberPosts
updates attributes from the passed in hash and  :readonly: To create a reader
saves the record. Ex: Post.find(:all, :readonly=>true)
CRUD-Read- Calculations
 :lock: Implement row level locking.
To perform aggregate operations
find_by_sql: Ex: Post.find(l, :lock=>true) #implements select for ..update command
 calculate(operation, column_name, options)
 :join: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id =
 average(column_name, options) Executes a custom sql query against the
 count(*args) id"
database. Columns are returned as attributes of
 maximum(column_name, options) Ex: Post.find(:all, :joins=>"JOIN topics ON posts.topic_id=topics.id JOIN authors ON
the calling Model.
 minimum(column_name,) topics.author_id=authors.id")
Ex: Post.find_by_sql “select a,b,c,d,e,f from
 sum(column_name, options)
tablename” #read post.a,post.b etc
Options include :distinct.

Vous aimerez peut-être aussi