Download - ActiveRecord Query Interface
ActiveRecord Query Interface 3.0
@tim_keller
Consultant at innoQ
OK. Let's Go!
In a Nutshell
The new AR Query Interface is:
Tasty!
That was it.
Just kidding!
Preamble
The new Query Interface is build on top of:
Active Relation
A GoogleSummerOfCode-Project that:
„...integrate Arel into the existing implementation of ActiveRecord...“
http://socghop.appspot.com/gsoc/student_project/show/google/gsoc2009/rails/t124025364581
„Arel is a Relational Algebra for Ruby“
http://github.com/rails/arel
And simplifies the generation of complex SQL queries
Show me some code!
Caution!
The „old“ ActiveRecord Query Interface will be deprecated in Rails 3.1 and fully removed in Rails 3.2!
The „options hash“ for ActiveRecord class methods is now deprecated
MyClass.find(:first) and MyClass.find(:last) are also
deprecated
Example (deprecated)
● Owner.find(:first)
● Owner.find(:first, :conditions => {:name => 'test'})
But that is OK:● Owner.find(1)
● Owner.find(1,2)
The „options hash“ for the Scope stuff is also deprecated
Example (deprecated)
● named_scope :red, :conditions => { :colour => 'red' }
● default_scope :order => 'last_name'
„named_scope“ is deprecated in Rails 3.0. Just use „scope“
The New Shit!
New finder methods
Example (New API)
● where
● having
● select
● group
● order
● limit
● offset
● joins
● includes
● lock
● readonly
● from
The return value is a ActiveRecord::Relation
Relations are lazy loaded!
Example
● Rails 2● Owner.find(:first, :conditions => {:name => 'test'})
● Rails 3● Owner.where(:name => 'test')● with DB-Query
– Owner.where(:name => 'test').each{ |o| puts o.name }
For Eager Loading use all(), first(), last()
Example
● Rails 2● Owner.find(:first, :conditions => {:name => 'test'})
● Rails 3● Owner.where(:name => 'test').first
Relations are chainable and „shareable“
Example
● Rails 3@books = Book.order(params[:order))
@published_books = @books.where(:published => true)
@unpublished_books = @books.where(:published => false)
Example
● Rails 2● Book.find(:all, :conditions => ["price <= ?", 10], :include => :authors)
● Rails 3● Book.where("price <= ?",10).includes(:authors)
named_scope => scope
Example
● Rails 2● named_scope :red, :conditions => { :colour => 'red' }
● Rails 3.0● scope :red, :conditions => { :colour => 'red' }
● Rails 3.2● scope :red, where(:colour => 'red')
Sources
● m.onkey.org/2010/1/22/active-record-query-interface
● magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/
● edgeapi.rubyonrails.org/● slideshare.net/GreggPollack/rails-3-beautiful-
code-3219240● flickr.com/photos/fofurasfelinas/2502823019/siz
es/o/
Sources
● flickr.com/photos/timcaynes/148110505/● flickr.com/photos/gurana/3831997459/sizes/m/
My two cents. Thank you!