SlideShare a Scribd company logo
1 of 54
Download to read offline
The 9th Round of ROR Lab.



Active Record
Query Interface(1)

      March 17th, 2012

       Hyoseong Choi
         ROR Lab.
ActiveRecord
• No more SQL statements     MySQL
                             PostgreSQL
  : select * from tables     SQLite
                             ...
                                  ORM
                                 Active
      • SQL query                Record

      • Fire                     Finder
      • Ruby object             Methods
      • after_find callback
                                     ROR Lab.
Finder Methods of
  ActiveRecord
1.where
2.select
3.group
4.order
5.reorder
6.reverse_order
7.limit
8.offset
9.joins
10.includes
11.lock
12.readonly
13.from
14.having

ActiveRecord::Relation
                         ROR Lab.
Retrieving
    A Single Object
• find
• first
• last
• first!
• last!
                  ROR Lab.
Retrieving
   A Single Object
                        - find -


  # Find the client with primary key (id) 10.

  client = Client.find(10)

  # => #<Client id: 10, first_name: "Ryan">



SELECT * FROM clients WHERE (clients.id = 10)

ActiveRecord::RecordNotFound exception


                                                ROR Lab.
Retrieving
   A Single Object
                       - first -


  client = Client.first

  # => #<Client id: 1, first_name: "Lifo">



SELECT * FROM clients LIMIT 1


nil if no matching record is found



                                             ROR Lab.
Retrieving
   A Single Object
                         - last -


  client = Client.last

  # => #<Client id: 221, first_name: "Russel">



SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1


nil if no matching record is found



                                                 ROR Lab.
Retrieving
   A Single Object
                      - first! -


  client = Client.first!

  # => #<Client id: 1, first_name: "Lifo">



SELECT * FROM clients LIMIT 1


RecordNotFound if no matching record



                                             ROR Lab.
Retrieving
   A Single Object
                      - last! -


  client = Client.last!

  # => #<Client id: 221, first_name: "Russel">



SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1


RecordNotFound if no matching record



                                                 ROR Lab.
Retrieving
  Multiple Objects
• Using multiple primary keys
• In batches
 • find_each :batch_size, :start,
 • find_in_batches :batch_size, :start
    + find options (except for :order, :limit)


                                         ROR Lab.
Retrieving
  Multiple Objects
         - Using multiple primary keys -

  # Find the clients with primary keys 1 and 10.
  client = Client.find([1, 10])
  # Or even Client.find(1, 10)
  # => [#<Client id: 1, first_name: "Lifo">,
  #<Client id: 10, first_name: "Ryan">]



SELECT * FROM clients WHERE (clients.id IN (1,10))

ActiveRecord::RecordNotFound exception


                                                   ROR Lab.
Retrieving
       Multiple Objects
                          - in Batches -
                 to iterate over a large set of records

• find_each : each record to the block individually as a model
• find_in_batches : the entire batch to the block as an array of models
       # This is very inefficient when the users table
       has thousands of rows.
       User.all.each do |user|
         NewsLetter.weekly_deliver(user)
       end
                                              OK to 1,000
                                                             ROR Lab.
Retrieving
Multiple Objects
          - in Batches : find_each -

User.find_each do |user|
  NewsLetter.weekly_deliver(user)
end

User.find_each(:batch_size => 5000) do |user|
  NewsLetter.weekly_deliver(user)
end

User.find_each(:start => 2000, :batch_size => 5000)
do |user|
  NewsLetter.weekly_deliver(user)
end



                                                ROR Lab.
Retrieving
  Multiple Objects
            - in Batches : find_each -

  Article.find_each { |a| ... } # => iterate over all
  articles, in chunks of 1000 (the default)

  Article.find_each(:conditions => { :published =>
  true }, :batch_size => 100 ) { |a| ... }
    # iterate over published articles in chunks of
  100




http://archives.ryandaigle.com/articles/
2009/2/23/what-s-new-in-edge-rails-batched-find

                                                     ROR Lab.
Retrieving
     Multiple Objects
            - in Batches : find_in_batches -

    # Give add_invoices an array of 1000 invoices at a
    time
    Invoice.find_in_batches(:include => :invoice_lines)
    do |invoices|
      export.add_invoices(invoices)
    end


options :
  • :batch_size & :start
  • options of find method (except :order and :limit)

                                                    ROR Lab.
Retrieving
  Multiple Objects
          - in Batches : find_in_batches -

Article.find_in_batches { |articles| articles.each { |
a| ... } } # => articles is array of size 1000
Article.find_in_batches(:batch_size => 100 ) { |articles|
articles.each { |a| ... } }
  # iterate over all articles in chunks of 100

class Article < ActiveRecord::Base
  scope :published, :conditions => { :published => true }
end

Article.published.find_in_batches(:batch_size => 100 )
{ |articles| ... }
  # iterate over published articles in chunks of 100



                                                    ROR Lab.
Conditions
               - where -


• String conditions
• Array conditions
• Hash conditions

                           ROR Lab.
String Conditions


 Client.where("orders_count = ‘2’")




                                      ROR Lab.
Array Conditions
Client.where("orders_count = ?", params[:orders])


Client.where("orders_count = ? AND locked = ?",
               params[:orders], false)



                                         X
Client.where("orders_count = #{params[:orders]}")


                         hacking!!! by SQL injection
 http://guides.rubyonrails.org/security.html#sql-injection


                                                        ROR Lab.
Array Conditions
         - Placeholder conditions -

Client.where("created_at >= :start_date AND
created_at <= :end_date", {:start_date =>
params[:start_date], :end_date =>
params[:end_date]})




                                              ROR Lab.
Array Conditions
              - Range conditions -


  Client.where(:created_at =>
  (params[:start_date].to_date)..
  (params[:end_date].to_date))




SELECT "clients".* FROM "clients" WHERE
("clients"."created_at" BETWEEN '2010-09-29' AND
'2010-11-30')




                                             ROR Lab.
Hash Conditions
           - Equality conditions -


Client.where(:locked => true)

Client.where('locked' => true)




                                     ROR Lab.
Hash Conditions
               - Range conditions -


  Client.where(:created_at => (Time.now.midnight -
  1.day)..Time.now.midnight)




SELECT * FROM clients WHERE (clients.created_at
BETWEEN '2008-12-21 00:00:00' AND '2008-12-22
00:00:00')




                                                  ROR Lab.
Hash Conditions
               - Subset conditions -


  Client.where(:orders_count => [1,3,5])



SELECT * FROM clients WHERE (clients.orders_count IN
(1,3,5))




                                                 ROR Lab.
Ordering

Client.order("created_at")

Client.order("created_at DESC")
# OR
Client.order("created_at ASC")

Client.order("orders_count ASC, created_at DESC")




                                                ROR Lab.
Selecting
If the select method is used, all the returning objects will be read only.



Client.select("viewable_by, locked")
    SELECT viewable_by, locked FROM clients
ActiveModel::MissingAttributeError: missing attribute: <attribute>



Client.select(:name).uniq
    SELECT DISTINCT name FROM clients


query = Client.select(:name).uniq
# => Returns unique names
query.uniq(false)
# => Returns all names, even if there are duplicates


                                                                     ROR Lab.
Limit & Offset
Client.limit(5)

  SELECT * FROM clients LIMIT 5

Client.limit(5).offset(30)

  SELECT * FROM clients LIMIT 5 OFFSET 30




                                            ROR Lab.
Group
  Order.select(
  "date(created_at) as ordered_date, sum(price) as
  total_price")
  .group("date(created_at)")




SQL
  SELECT date(created_at) as ordered_date, sum(price)
  as total_price FROM orders GROUP BY
  date(created_at)




                                                     ROR Lab.
Having
  Order.select(
  "date(created_at) as ordered_date, sum(price) as
  total_price")
  .group("date(created_at)")
  .having("sum(price) > ?", 100)


SQL
  SELECT date(created_at) as ordered_date, sum(price)
  as total_price FROM orders GROUP BY
  date(created_at) HAVING sum(price) > 100




                                                     ROR Lab.
Overriding
       Conditions
• except
• only
• reorder
• reverse_order

                    ROR Lab.
Overriding
             Conditions
                         - except -

Post.where('id > 10').limit(20).order('id asc').except(:order)



          SELECT * FROM posts WHERE id > 10 LIMIT 20




                                                       ROR Lab.
Overriding
                 Conditions
                              - only -

Post.where('id > 10').limit(20).order('id desc').only(:order, :where)


         SELECT * FROM posts WHERE id > 10 ORDER BY id DESC




                                                         ROR Lab.
Overriding
         Conditions
                     - reorder -
 class Post < ActiveRecord::Base
   ..
   ..
   has_many :comments, :order => 'posted_at DESC'
 end
  
 Post.find(10).comments.reorder('name')



SELECT * FROM posts WHERE id = 10 ORDER BY name

SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC


                                                    ROR Lab.
Overriding
              Conditions
                      - reverse_order -

 Client.where("orders_count > 10").order(:name).reverse_order


SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC


 Client.where("orders_count > 10").reverse_order


SELECT * FROM clients WHERE orders_count > 10 ORDER BY
clients.id DESC


                                                         ROR Lab.
Readonly Objects
client = Client.readonly.first
client.visits += 1
client.save




    ActiveRecord::ReadOnlyRecord exception




                                      ROR Lab.
Locking Records
    for Update
• To prevent “race conditions”
• To ensure “atomic updates”
• Two locking mechanisms
  ‣ Optimistic Locking : version control
  ‣ Pessimistic Locking : DB lock

                                       ROR Lab.
Optimistic Locking
• “lock_version” in DB table (default to 0)
• set_locking_column to change column name
  c1 = Client.find(1)
  c2 = Client.find(1)
   
  c1.first_name = "Michael"
  c1.save # increments the lock_version column
   
  c2.name = "should fail"
  c2.save # Raises an ActiveRecord::StaleObjectError



                                                  ROR Lab.
Optimistic Locking
• To turn off,
  ActiveRecord::Base.lock_optimistically = false

• To override the name of the lock_version
  column

  class Client < ActiveRecord::Base
    set_locking_column :lock_client_column
  end




                                             ROR Lab.
Pessimistic Locking

• A locking mechanism by DB
• An exclusive lock on the selected rows
• Usually wrapped inside a transaction
• Two types of Lock
  ‣ FOR UPDATE (default, an exclusive lock)
  ‣ LOCK IN SHARE MODE

                                              ROR Lab.
Pessimistic Locking
  Item.transaction do
    i = Item.lock.first
    i.name = 'Jones'
    i.save
  end



 SQL (0.2ms)   BEGIN
 Item Load (0.3ms)   SELECT * FROM `items` LIMIT 1 FOR UPDATE
 Item Update (0.4ms)   UPDATE `items` SET `updated_at` =
 '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
 SQL (0.8ms)   COMMIT




                                                           ROR Lab.
Pessimistic Locking
 Item.transaction do
   i = Item.lock("LOCK IN SHARE MODE").find(1)
   i.increment!(:views)
 end




 item = Item.first
 item.with_lock do
   # This block is called within a transaction,
   # item is already locked.
   item.increment!(:views)
 end




                                                  ROR Lab.
Joining Tables
       - Using a String SQL Fragment -


 Client.joins('LEFT OUTER JOIN addresses ON
 addresses.client_id = clients.id')



SELECT clients.*
FROM clients
LEFT OUTER JOIN addresses
ON addresses.client_id = clients.id




                                              ROR Lab.
Joining Tables
- Using Array/Hash of Named Associations -

           only with INNER JOIN


• a Single Association
• Multiple Associations
• Nested Associations(Single Level)
• Nested Associations(Multiple Level)




                                        ROR Lab.
Joining Tables
         - Using Array/Hash of Named Associations -

                                        only with INNER JOIN
class Category < ActiveRecord::Base
  has_many :posts
end
 
class Post < ActiveRecord::Base       • a Single Association
  belongs_to :category
  has_many :comments
  has_many :tags
end                                       Category.joins(:posts)
 
class Comment < ActiveRecord::Base
  belongs_to :post
  has_one :guest
end                                     SELECT categories.*
                                          FROM categories
class Guest < ActiveRecord::Base
                                          INNER JOIN posts
  belongs_to :comment
end                                       ON posts.category_id = categories.id
 
class Tag < ActiveRecord::Base
  belongs_to :post                      “return a Category object for all categories with posts”
end

                                                                                ROR Lab.
Joining Tables
         - Using Array/Hash of Named Associations -

                                        only with INNER JOIN
class Category < ActiveRecord::Base
  has_many :posts
end
 
class Post < ActiveRecord::Base       • Multiple Associations
  belongs_to :category
  has_many :comments
  has_many :tags
end                                       Post.joins(:category, :comments)
 
class Comment < ActiveRecord::Base
  belongs_to :post
  has_one :guest
                                        SELECT posts.* FROM posts
end
                                          INNER JOIN categories
class Guest < ActiveRecord::Base            ON posts.category_id = categories.id
  belongs_to :comment                     INNER JOIN comments
end                                         ON comments.post_id = posts.id
 
class Tag < ActiveRecord::Base
                                        “return all posts that have a category and at least one comment”
  belongs_to :post
end

                                                                                  ROR Lab.
Joining Tables
         - Using Array/Hash of Named Associations -

                                        only with INNER JOIN
class Category < ActiveRecord::Base
  has_many :posts
end
 
class Post < ActiveRecord::Base       • Nested Associations(Single Level)
  belongs_to :category
  has_many :comments
  has_many :tags
end                                      Post.joins(:comments => :guest)
 
class Comment < ActiveRecord::Base
  belongs_to :post
  has_one :guest
                                        SELECT posts.* FROM posts
end
                                          INNER JOIN comments
class Guest < ActiveRecord::Base            ON comments.post_id = posts.id
  belongs_to :comment                     INNER JOIN guests
end                                         ON guests.comment_id = comments.id
 
class Tag < ActiveRecord::Base
  belongs_to :post                     “return all posts that have a comment made by a guest”
end

                                                                              ROR Lab.
Joining Tables
         - Using Array/Hash of Named Associations -

                                        only with INNER JOIN
class Category < ActiveRecord::Base
  has_many :posts
end
 
class Post < ActiveRecord::Base       • Nested Associations(Multiple Level)
  belongs_to :category
  has_many :comments
  has_many :tags
end                                       Category.joins(:posts =>
 
class Comment < ActiveRecord::Base
                                          [{:comments => :guest}, :tags]
  belongs_to :post
  has_one :guest
end
                                        SELECT categories.* FROM categories
class Guest < ActiveRecord::Base          INNER JOIN posts ON posts.category_id = categories.id
  belongs_to :comment
                                          INNER JOIN comments ON comments.post_id = posts.id
end
                                          INNER JOIN guests ON guests.id = comments.quest_id
class Tag < ActiveRecord::Base            INNER JOIN tags ON tags.post_id = posts.id
  belongs_to :post
end

                                                                             ROR Lab.
Joining Tables
  - Specifying Conditions on the Joined Tables -

: using Array and String Conditions

 time_range = (Time.now.midnight - 1.day)..Time.now.midnight
 Client.joins(:orders)
       .where('orders.created_at' => time_range)


: using nested Hash Conditions

 time_range = (Time.now.midnight - 1.day)..Time.now.midnight
 Client.joins(:orders)
       .where(:orders => {:created_at => time_range})


                                                     ROR Lab.
Joining Tables
    - Inner Join -




   SELECT <select_list>
   FROM TableA A
   INNER JOIN TableB B
   ON A.Key = B.Key



                          ROR Lab.
Joining Tables
              - Left Join -




SELECT <select_list>   SELECT <select_list>
FROM TableA A          FROM TableA A
LEFT JOIN TableB B     LEFT JOIN TableB B
ON A.Key = B.Key       ON A.Key = B.Key
                       WHERE B.Key IS NULL

                                        ROR Lab.
Joining Tables
             - Right Join -




SELECT <select_list>   SELECT <select_list>
FROM TableA A          FROM TableA A
RIGHT JOIN TableB B    RIGHT JOIN TableB B
ON A.Key = B.Key       ON A.Key = B.Key
                       WHERE A.Key IS NULL

                                        ROR Lab.
Joining Tables
           - Full Outer Join -




SELECT <select_list>     SELECT <select_list>
FROM TableA A            FROM TableA A
FULL OUTER JOIN TableB B FULL OUTER JOIN TableB B
ON A.Key = B.Key         ON A.Key = B.Key
                         WHERE A.Key IS NULL
                         OR B.Key IS NULL
                                            ROR Lab.
ROR Lab.
감사합니다.

More Related Content

What's hot

분산저장시스템 개발에 대한 12가지 이야기
분산저장시스템 개발에 대한 12가지 이야기분산저장시스템 개발에 대한 12가지 이야기
분산저장시스템 개발에 대한 12가지 이야기NAVER D2
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
Common MongoDB Use Cases
Common MongoDB Use Cases Common MongoDB Use Cases
Common MongoDB Use Cases MongoDB
 
JBoss Drools - Pure Java Rule Engine
JBoss Drools - Pure Java Rule EngineJBoss Drools - Pure Java Rule Engine
JBoss Drools - Pure Java Rule EngineAnil Allewar
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교Woo Yeong Choi
 
Python and MongoDB as a Market Data Platform by James Blackburn
Python and MongoDB as a Market Data Platform by James BlackburnPython and MongoDB as a Market Data Platform by James Blackburn
Python and MongoDB as a Market Data Platform by James BlackburnPyData
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architectureAmit Bhalla
 
MongoDB Administration 101
MongoDB Administration 101MongoDB Administration 101
MongoDB Administration 101MongoDB
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재PgDay.Seoul
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)Uwe Printz
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkStefano Paluello
 
Migrating from RDBMS to MongoDB
Migrating from RDBMS to MongoDBMigrating from RDBMS to MongoDB
Migrating from RDBMS to MongoDBMongoDB
 
"Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2...
"Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2..."Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2...
"Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2...Markus Michalewicz
 
MySQL enterprise backup overview
MySQL enterprise backup overviewMySQL enterprise backup overview
MySQL enterprise backup overview郁萍 王
 
Getting started with postgresql
Getting started with postgresqlGetting started with postgresql
Getting started with postgresqlbotsplash.com
 
MySQL Shell - the best DBA tool !
MySQL Shell - the best DBA tool !MySQL Shell - the best DBA tool !
MySQL Shell - the best DBA tool !Frederic Descamps
 
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Julian Hyde
 
스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기 스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기 Chanwook Park
 

What's hot (20)

분산저장시스템 개발에 대한 12가지 이야기
분산저장시스템 개발에 대한 12가지 이야기분산저장시스템 개발에 대한 12가지 이야기
분산저장시스템 개발에 대한 12가지 이야기
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
Common MongoDB Use Cases
Common MongoDB Use Cases Common MongoDB Use Cases
Common MongoDB Use Cases
 
JBoss Drools - Pure Java Rule Engine
JBoss Drools - Pure Java Rule EngineJBoss Drools - Pure Java Rule Engine
JBoss Drools - Pure Java Rule Engine
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교
 
Python and MongoDB as a Market Data Platform by James Blackburn
Python and MongoDB as a Market Data Platform by James BlackburnPython and MongoDB as a Market Data Platform by James Blackburn
Python and MongoDB as a Market Data Platform by James Blackburn
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architecture
 
MongoDB Administration 101
MongoDB Administration 101MongoDB Administration 101
MongoDB Administration 101
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
 
284
284284
284
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Migrating from RDBMS to MongoDB
Migrating from RDBMS to MongoDBMigrating from RDBMS to MongoDB
Migrating from RDBMS to MongoDB
 
"Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2...
"Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2..."Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2...
"Changing Role of the DBA" Skills to Have, to Obtain & to Nurture - Updated 2...
 
MySQL enterprise backup overview
MySQL enterprise backup overviewMySQL enterprise backup overview
MySQL enterprise backup overview
 
Getting started with postgresql
Getting started with postgresqlGetting started with postgresql
Getting started with postgresql
 
MySQL Shell - the best DBA tool !
MySQL Shell - the best DBA tool !MySQL Shell - the best DBA tool !
MySQL Shell - the best DBA tool !
 
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
 
스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기 스프링처럼 JDBC 리팩터링하기
스프링처럼 JDBC 리팩터링하기
 
Get to know PostgreSQL!
Get to know PostgreSQL!Get to know PostgreSQL!
Get to know PostgreSQL!
 

Viewers also liked

Make your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On RailsMake your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On RailsNataly Tkachuk
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2RORLAB
 
6 reasons Jubilee could be a Rubyist's new best friend
6 reasons Jubilee could be a Rubyist's new best friend6 reasons Jubilee could be a Rubyist's new best friend
6 reasons Jubilee could be a Rubyist's new best friendForrest Chang
 
ActiveWarehouse/ETL - BI & DW for Ruby/Rails
ActiveWarehouse/ETL - BI & DW for Ruby/RailsActiveWarehouse/ETL - BI & DW for Ruby/Rails
ActiveWarehouse/ETL - BI & DW for Ruby/RailsPaul Gallagher
 
Performance Optimization of Rails Applications
Performance Optimization of Rails ApplicationsPerformance Optimization of Rails Applications
Performance Optimization of Rails ApplicationsSerge Smetana
 
Neev Expertise in Ruby on Rails (RoR)
Neev Expertise in Ruby on Rails (RoR)Neev Expertise in Ruby on Rails (RoR)
Neev Expertise in Ruby on Rails (RoR)Neev Technologies
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsAgnieszka Figiel
 
Distributed Ruby and Rails
Distributed Ruby and RailsDistributed Ruby and Rails
Distributed Ruby and RailsWen-Tien Chang
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVMPhil Calçado
 
Ruby On Rails Introduction
Ruby On Rails IntroductionRuby On Rails Introduction
Ruby On Rails IntroductionThomas Fuchs
 
Design in Tech Report 2017
Design in Tech Report 2017Design in Tech Report 2017
Design in Tech Report 2017John Maeda
 

Viewers also liked (14)

Make your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On RailsMake your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On Rails
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 
6 reasons Jubilee could be a Rubyist's new best friend
6 reasons Jubilee could be a Rubyist's new best friend6 reasons Jubilee could be a Rubyist's new best friend
6 reasons Jubilee could be a Rubyist's new best friend
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 
ActiveWarehouse/ETL - BI & DW for Ruby/Rails
ActiveWarehouse/ETL - BI & DW for Ruby/RailsActiveWarehouse/ETL - BI & DW for Ruby/Rails
ActiveWarehouse/ETL - BI & DW for Ruby/Rails
 
Performance Optimization of Rails Applications
Performance Optimization of Rails ApplicationsPerformance Optimization of Rails Applications
Performance Optimization of Rails Applications
 
Neev Expertise in Ruby on Rails (RoR)
Neev Expertise in Ruby on Rails (RoR)Neev Expertise in Ruby on Rails (RoR)
Neev Expertise in Ruby on Rails (RoR)
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Distributed Ruby and Rails
Distributed Ruby and RailsDistributed Ruby and Rails
Distributed Ruby and Rails
 
Ruby Beyond Rails
Ruby Beyond RailsRuby Beyond Rails
Ruby Beyond Rails
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVM
 
Ruby On Rails Introduction
Ruby On Rails IntroductionRuby On Rails Introduction
Ruby On Rails Introduction
 
Design in Tech Report 2017
Design in Tech Report 2017Design in Tech Report 2017
Design in Tech Report 2017
 

Similar to ActiveRecord Query Interface (1), Season 1

Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1RORLAB
 
Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumAlina Vilk
 
Maior performance no seu sistema com o uso adequado de orm em rails
Maior performance no seu sistema com o uso adequado de orm em railsMaior performance no seu sistema com o uso adequado de orm em rails
Maior performance no seu sistema com o uso adequado de orm em railsIsaac de Souza
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex Sujit Kumar
 
performance vamos dormir mais?
performance vamos dormir mais?performance vamos dormir mais?
performance vamos dormir mais?tdc-globalcode
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1RORLAB
 
Solr introduction
Solr introductionSolr introduction
Solr introductionLap Tran
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Wongnai
 
Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19
Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19
Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19Henrik Ingo
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Drivers APIs and Looking Forward
Drivers APIs and Looking ForwardDrivers APIs and Looking Forward
Drivers APIs and Looking ForwardMongoDB
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB AppHenrik Ingo
 

Similar to ActiveRecord Query Interface (1), Season 1 (20)

Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1
 
Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, Ciklum
 
Maior performance no seu sistema com o uso adequado de orm em rails
Maior performance no seu sistema com o uso adequado de orm em railsMaior performance no seu sistema com o uso adequado de orm em rails
Maior performance no seu sistema com o uso adequado de orm em rails
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex
 
performance vamos dormir mais?
performance vamos dormir mais?performance vamos dormir mais?
performance vamos dormir mais?
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1
 
Oracle adapters for Ruby ORMs
Oracle adapters for Ruby ORMsOracle adapters for Ruby ORMs
Oracle adapters for Ruby ORMs
 
Solr introduction
Solr introductionSolr introduction
Solr introduction
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19
Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19
Whats new in mongoDB 2.4 at Copenhagen user group 2013-06-19
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Drivers APIs and Looking Forward
Drivers APIs and Looking ForwardDrivers APIs and Looking Forward
Drivers APIs and Looking Forward
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
 

More from RORLAB

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4) RORLAB
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3) RORLAB
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)RORLAB
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)RORLAB
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record associationRORLAB
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsRORLAB
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개RORLAB
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2RORLAB
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2RORLAB
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2RORLAB
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2RORLAB
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2RORLAB
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2RORLAB
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2RORLAB
 

More from RORLAB (20)

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4)
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3)
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2
 

Recently uploaded

4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 

Recently uploaded (20)

4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 

ActiveRecord Query Interface (1), Season 1

  • 1. The 9th Round of ROR Lab. Active Record Query Interface(1) March 17th, 2012 Hyoseong Choi ROR Lab.
  • 2. ActiveRecord • No more SQL statements MySQL PostgreSQL : select * from tables SQLite ... ORM Active • SQL query Record • Fire Finder • Ruby object Methods • after_find callback ROR Lab.
  • 3. Finder Methods of ActiveRecord 1.where 2.select 3.group 4.order 5.reorder 6.reverse_order 7.limit 8.offset 9.joins 10.includes 11.lock 12.readonly 13.from 14.having ActiveRecord::Relation ROR Lab.
  • 4. Retrieving A Single Object • find • first • last • first! • last! ROR Lab.
  • 5. Retrieving A Single Object - find - # Find the client with primary key (id) 10. client = Client.find(10) # => #<Client id: 10, first_name: "Ryan"> SELECT * FROM clients WHERE (clients.id = 10) ActiveRecord::RecordNotFound exception ROR Lab.
  • 6. Retrieving A Single Object - first - client = Client.first # => #<Client id: 1, first_name: "Lifo"> SELECT * FROM clients LIMIT 1 nil if no matching record is found ROR Lab.
  • 7. Retrieving A Single Object - last - client = Client.last # => #<Client id: 221, first_name: "Russel"> SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 nil if no matching record is found ROR Lab.
  • 8. Retrieving A Single Object - first! - client = Client.first! # => #<Client id: 1, first_name: "Lifo"> SELECT * FROM clients LIMIT 1 RecordNotFound if no matching record ROR Lab.
  • 9. Retrieving A Single Object - last! - client = Client.last! # => #<Client id: 221, first_name: "Russel"> SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 RecordNotFound if no matching record ROR Lab.
  • 10. Retrieving Multiple Objects • Using multiple primary keys • In batches • find_each :batch_size, :start, • find_in_batches :batch_size, :start + find options (except for :order, :limit) ROR Lab.
  • 11. Retrieving Multiple Objects - Using multiple primary keys - # Find the clients with primary keys 1 and 10. client = Client.find([1, 10]) # Or even Client.find(1, 10) # => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">] SELECT * FROM clients WHERE (clients.id IN (1,10)) ActiveRecord::RecordNotFound exception ROR Lab.
  • 12. Retrieving Multiple Objects - in Batches - to iterate over a large set of records • find_each : each record to the block individually as a model • find_in_batches : the entire batch to the block as an array of models # This is very inefficient when the users table has thousands of rows. User.all.each do |user|   NewsLetter.weekly_deliver(user) end OK to 1,000 ROR Lab.
  • 13. Retrieving Multiple Objects - in Batches : find_each - User.find_each do |user|   NewsLetter.weekly_deliver(user) end User.find_each(:batch_size => 5000) do |user|   NewsLetter.weekly_deliver(user) end User.find_each(:start => 2000, :batch_size => 5000) do |user|   NewsLetter.weekly_deliver(user) end ROR Lab.
  • 14. Retrieving Multiple Objects - in Batches : find_each - Article.find_each { |a| ... } # => iterate over all articles, in chunks of 1000 (the default) Article.find_each(:conditions => { :published => true }, :batch_size => 100 ) { |a| ... } # iterate over published articles in chunks of 100 http://archives.ryandaigle.com/articles/ 2009/2/23/what-s-new-in-edge-rails-batched-find ROR Lab.
  • 15. Retrieving Multiple Objects - in Batches : find_in_batches - # Give add_invoices an array of 1000 invoices at a time Invoice.find_in_batches(:include => :invoice_lines) do |invoices|   export.add_invoices(invoices) end options : • :batch_size & :start • options of find method (except :order and :limit) ROR Lab.
  • 16. Retrieving Multiple Objects - in Batches : find_in_batches - Article.find_in_batches { |articles| articles.each { | a| ... } } # => articles is array of size 1000 Article.find_in_batches(:batch_size => 100 ) { |articles| articles.each { |a| ... } } # iterate over all articles in chunks of 100 class Article < ActiveRecord::Base scope :published, :conditions => { :published => true } end Article.published.find_in_batches(:batch_size => 100 ) { |articles| ... } # iterate over published articles in chunks of 100 ROR Lab.
  • 17. Conditions - where - • String conditions • Array conditions • Hash conditions ROR Lab.
  • 19. Array Conditions Client.where("orders_count = ?", params[:orders]) Client.where("orders_count = ? AND locked = ?", params[:orders], false) X Client.where("orders_count = #{params[:orders]}") hacking!!! by SQL injection http://guides.rubyonrails.org/security.html#sql-injection ROR Lab.
  • 20. Array Conditions - Placeholder conditions - Client.where("created_at >= :start_date AND created_at <= :end_date", {:start_date => params[:start_date], :end_date => params[:end_date]}) ROR Lab.
  • 21. Array Conditions - Range conditions - Client.where(:created_at => (params[:start_date].to_date).. (params[:end_date].to_date)) SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30') ROR Lab.
  • 22. Hash Conditions - Equality conditions - Client.where(:locked => true) Client.where('locked' => true) ROR Lab.
  • 23. Hash Conditions - Range conditions - Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight) SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00') ROR Lab.
  • 24. Hash Conditions - Subset conditions - Client.where(:orders_count => [1,3,5]) SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) ROR Lab.
  • 25. Ordering Client.order("created_at") Client.order("created_at DESC") # OR Client.order("created_at ASC") Client.order("orders_count ASC, created_at DESC") ROR Lab.
  • 26. Selecting If the select method is used, all the returning objects will be read only. Client.select("viewable_by, locked") SELECT viewable_by, locked FROM clients ActiveModel::MissingAttributeError: missing attribute: <attribute> Client.select(:name).uniq SELECT DISTINCT name FROM clients query = Client.select(:name).uniq # => Returns unique names query.uniq(false) # => Returns all names, even if there are duplicates ROR Lab.
  • 27. Limit & Offset Client.limit(5) SELECT * FROM clients LIMIT 5 Client.limit(5).offset(30) SELECT * FROM clients LIMIT 5 OFFSET 30 ROR Lab.
  • 28. Group Order.select( "date(created_at) as ordered_date, sum(price) as total_price") .group("date(created_at)") SQL SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) ROR Lab.
  • 29. Having Order.select( "date(created_at) as ordered_date, sum(price) as total_price") .group("date(created_at)") .having("sum(price) > ?", 100) SQL SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100 ROR Lab.
  • 30. Overriding Conditions • except • only • reorder • reverse_order ROR Lab.
  • 31. Overriding Conditions - except - Post.where('id > 10').limit(20).order('id asc').except(:order) SELECT * FROM posts WHERE id > 10 LIMIT 20 ROR Lab.
  • 32. Overriding Conditions - only - Post.where('id > 10').limit(20).order('id desc').only(:order, :where) SELECT * FROM posts WHERE id > 10 ORDER BY id DESC ROR Lab.
  • 33. Overriding Conditions - reorder - class Post < ActiveRecord::Base   ..   ..   has_many :comments, :order => 'posted_at DESC' end   Post.find(10).comments.reorder('name') SELECT * FROM posts WHERE id = 10 ORDER BY name SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC ROR Lab.
  • 34. Overriding Conditions - reverse_order - Client.where("orders_count > 10").order(:name).reverse_order SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC Client.where("orders_count > 10").reverse_order SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC ROR Lab.
  • 35. Readonly Objects client = Client.readonly.first client.visits += 1 client.save ActiveRecord::ReadOnlyRecord exception ROR Lab.
  • 36. Locking Records for Update • To prevent “race conditions” • To ensure “atomic updates” • Two locking mechanisms ‣ Optimistic Locking : version control ‣ Pessimistic Locking : DB lock ROR Lab.
  • 37. Optimistic Locking • “lock_version” in DB table (default to 0) • set_locking_column to change column name c1 = Client.find(1) c2 = Client.find(1)   c1.first_name = "Michael" c1.save # increments the lock_version column   c2.name = "should fail" c2.save # Raises an ActiveRecord::StaleObjectError ROR Lab.
  • 38. Optimistic Locking • To turn off, ActiveRecord::Base.lock_optimistically = false • To override the name of the lock_version column class Client < ActiveRecord::Base   set_locking_column :lock_client_column end ROR Lab.
  • 39. Pessimistic Locking • A locking mechanism by DB • An exclusive lock on the selected rows • Usually wrapped inside a transaction • Two types of Lock ‣ FOR UPDATE (default, an exclusive lock) ‣ LOCK IN SHARE MODE ROR Lab.
  • 40. Pessimistic Locking Item.transaction do   i = Item.lock.first   i.name = 'Jones'   i.save end SQL (0.2ms)   BEGIN Item Load (0.3ms)   SELECT * FROM `items` LIMIT 1 FOR UPDATE Item Update (0.4ms)   UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1 SQL (0.8ms)   COMMIT ROR Lab.
  • 41. Pessimistic Locking Item.transaction do   i = Item.lock("LOCK IN SHARE MODE").find(1)   i.increment!(:views) end item = Item.first item.with_lock do   # This block is called within a transaction,   # item is already locked.   item.increment!(:views) end ROR Lab.
  • 42. Joining Tables - Using a String SQL Fragment - Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id') SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id ROR Lab.
  • 43. Joining Tables - Using Array/Hash of Named Associations - only with INNER JOIN • a Single Association • Multiple Associations • Nested Associations(Single Level) • Nested Associations(Multiple Level) ROR Lab.
  • 44. Joining Tables - Using Array/Hash of Named Associations - only with INNER JOIN class Category < ActiveRecord::Base   has_many :posts end   class Post < ActiveRecord::Base • a Single Association   belongs_to :category   has_many :comments   has_many :tags end Category.joins(:posts)   class Comment < ActiveRecord::Base   belongs_to :post   has_one :guest end SELECT categories.*   FROM categories class Guest < ActiveRecord::Base   INNER JOIN posts   belongs_to :comment end ON posts.category_id = categories.id   class Tag < ActiveRecord::Base   belongs_to :post “return a Category object for all categories with posts” end ROR Lab.
  • 45. Joining Tables - Using Array/Hash of Named Associations - only with INNER JOIN class Category < ActiveRecord::Base   has_many :posts end   class Post < ActiveRecord::Base • Multiple Associations   belongs_to :category   has_many :comments   has_many :tags end Post.joins(:category, :comments)   class Comment < ActiveRecord::Base   belongs_to :post   has_one :guest SELECT posts.* FROM posts end     INNER JOIN categories class Guest < ActiveRecord::Base ON posts.category_id = categories.id   belongs_to :comment   INNER JOIN comments end ON comments.post_id = posts.id   class Tag < ActiveRecord::Base “return all posts that have a category and at least one comment”   belongs_to :post end ROR Lab.
  • 46. Joining Tables - Using Array/Hash of Named Associations - only with INNER JOIN class Category < ActiveRecord::Base   has_many :posts end   class Post < ActiveRecord::Base • Nested Associations(Single Level)   belongs_to :category   has_many :comments   has_many :tags end Post.joins(:comments => :guest)   class Comment < ActiveRecord::Base   belongs_to :post   has_one :guest SELECT posts.* FROM posts end     INNER JOIN comments class Guest < ActiveRecord::Base ON comments.post_id = posts.id   belongs_to :comment   INNER JOIN guests end ON guests.comment_id = comments.id   class Tag < ActiveRecord::Base   belongs_to :post “return all posts that have a comment made by a guest” end ROR Lab.
  • 47. Joining Tables - Using Array/Hash of Named Associations - only with INNER JOIN class Category < ActiveRecord::Base   has_many :posts end   class Post < ActiveRecord::Base • Nested Associations(Multiple Level)   belongs_to :category   has_many :comments   has_many :tags end Category.joins(:posts =>   class Comment < ActiveRecord::Base [{:comments => :guest}, :tags]   belongs_to :post   has_one :guest end   SELECT categories.* FROM categories class Guest < ActiveRecord::Base   INNER JOIN posts ON posts.category_id = categories.id   belongs_to :comment INNER JOIN comments ON comments.post_id = posts.id end   INNER JOIN guests ON guests.id = comments.quest_id class Tag < ActiveRecord::Base INNER JOIN tags ON tags.post_id = posts.id   belongs_to :post end ROR Lab.
  • 48. Joining Tables - Specifying Conditions on the Joined Tables - : using Array and String Conditions time_range = (Time.now.midnight - 1.day)..Time.now.midnight Client.joins(:orders) .where('orders.created_at' => time_range) : using nested Hash Conditions time_range = (Time.now.midnight - 1.day)..Time.now.midnight Client.joins(:orders) .where(:orders => {:created_at => time_range}) ROR Lab.
  • 49. Joining Tables - Inner Join - SELECT <select_list> FROM TableA A INNER JOIN TableB B ON A.Key = B.Key ROR Lab.
  • 50. Joining Tables - Left Join - SELECT <select_list> SELECT <select_list> FROM TableA A FROM TableA A LEFT JOIN TableB B LEFT JOIN TableB B ON A.Key = B.Key ON A.Key = B.Key WHERE B.Key IS NULL ROR Lab.
  • 51. Joining Tables - Right Join - SELECT <select_list> SELECT <select_list> FROM TableA A FROM TableA A RIGHT JOIN TableB B RIGHT JOIN TableB B ON A.Key = B.Key ON A.Key = B.Key WHERE A.Key IS NULL ROR Lab.
  • 52. Joining Tables - Full Outer Join - SELECT <select_list> SELECT <select_list> FROM TableA A FROM TableA A FULL OUTER JOIN TableB B FULL OUTER JOIN TableB B ON A.Key = B.Key ON A.Key = B.Key WHERE A.Key IS NULL OR B.Key IS NULL ROR Lab.
  • 55.   ROR Lab.

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n