SlideShare a Scribd company logo
Возможности,
особенности и
проблемы AR::Relation
Тимофей Цветков, Evil Martians
2011
Тимофей Цветков
2kan@evilmartians.com
Мотивации слайд
Я сказал убей!
Look at them!
SO HAPPY OMG
OMG LOL
ActiveRecord — не
черный ящик
Not only Arel
• Queries are not only Arel
• AR ≠ Arel
3.x (x ≤1)
• It’s not only Arel! AR::Relation was released
• Identity Map (WHORRAAAA)
ActiveRecord
module ActiveRecord #:nodoc:
class << self # Class methods
delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to
=> :scoped
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to
=> :scoped
delegate :find_each, :find_in_batches, :to => :scoped
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where,
:preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to
=> :scoped
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
end
end
Scoped
def scoped(options = nil)
if options
scoped.apply_finder_options(options)
else
if current_scope
current_scope.clone
else
scope = relation.clone
scope.default_scoped = true
scope
end
end
end
Finder methods
• where
• having
• select
• order
• limit
• offset
All finder methods work through AR::Relation
• joins
• includes
• lock
• readonly
• from
Example.Where
def where(opts, *rest)
return self if opts.blank?
relation = clone
relation.where_values += build_where(opts, rest)
relation
end
ActiveRecord::Relation
def to_a
@records = if @readonly_value.nil? && !@klass.locking_enabled?
eager_loading? ? find_with_associations : @klass.find_by_sql
(arel.to_sql, @bind_values)
else
IdentityMap.without do
eager_loading? ? find_with_associations : @klass.find_by_sql
(arel.to_sql, @bind_values)
end
end
end
Real quering from the AR::Relation
AR::Relation problems
• merging default_scope’s with labmda (solved):
default_scope where(:name => "qwerty")
default_scope lambda { order("id DESC") }
• except (I’ve wrote a patch):
scope :xxx, order("id DESC")
scope :yyy, except(:order).order("id ASC")
@surveys = Survey.xxx.yyy
Survey Load (0.1ms) SELECT "surveys".* FROM "surveys" ORDER BY id DESC, id ASC
IdentityMap
Identity map was written by Emilio Tagua
Emilio Tagua
LEHAIM!
Without IdentityMap
user1 = User.find(1) # => #<User id: 1, name: "Josh">
user2 = User.find(1) # => #<User id: 1, name: "Josh">
user1 == user2 # => true, b/c AR::Base recognizes that
# they have the same primary key
user1.object_id == user2.object_id # => false, b/c these are two
# different in-memory objects
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Code example from: http://edgerails.info/articles/what-s-new-in-edge-rails/2011/04/21/activerecord-identity-
map/index.html
With IdentityMap
user1 = User.find(1) # => #<User id: 1, name: "Josh">
user2 = User.find(1) # => #<User id: 1, name: "Josh">
user1 == user2 # => true
user1.object_id == user2.object_id # => true, b/c these really are
# the same in-memory objects
User Load (2.2ms) SELECT "users".* FROM "users" LIMIT 1
User with ID = 1 loaded from Identity Map
Code example from: http://edgerails.info/articles/what-s-new-in-edge-rails/2011/04/21/activerecord-identity-
map/index.html
Even more...
post = Post.find(1)
same_post = post.comments.first.post
post.object_id == same_post.object_id # => true
Code example from: http://miloops.com/post/3391477665/identity-map-and-active-record
Thread safe
• Creates for each request
• Uses Thread.current
def repository
Thread.current[:identity_map] ||= Hash.new { |h,k| h[k] = {} }
end
Interesting...
def update
@survey = Survey.find(params[:id])
@surveys = Survey.all
if @survey.update_attributes(params[:survey])
redirect_to(@survey, :notice => 'Survey was successfully updated.')
else
render :action => "edit"
end
end
def update
@survey = Survey.find(params[:id])
if @survey.update_attributes(params[:survey])
redirect_to(@survey, :notice => 'Survey was successfully updated.')
else
@surveys = Survey.all
render :action => "edit"
end
end
How to use
IdentityMap
• It will be in Rails 3.1
• To enable write in your application.rb:
config.active_record.identity_map = true
Contribute!!!112233
Троллинг

More Related Content

What's hot

jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionPaul Irish
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»e-Legion
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better Security
Colin O'Dell
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016
Colin O'Dell
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9
Bongwon Lee
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In RailsLouie Zhao
 
Boost Multi Index
Boost Multi IndexBoost Multi Index
Boost Multi Index
Sławomir Zborowski
 
Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASP
Mizno Kruge
 
Dollar symbol
Dollar symbolDollar symbol
Dollar symbol
Aaron Huang
 
HadoopとMongoDBを活用したソーシャルアプリのログ解析
HadoopとMongoDBを活用したソーシャルアプリのログ解析HadoopとMongoDBを活用したソーシャルアプリのログ解析
HadoopとMongoDBを活用したソーシャルアプリのログ解析Takahiro Inoue
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Simon Willison
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and Monitoring
Burt Beckwith
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First Widget
Chris Wilcoxson
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
Bedis ElAchèche
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
Chris Reynolds
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
Marcello Duarte
 

What's hot (20)

jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better Security
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In Rails
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Boost Multi Index
Boost Multi IndexBoost Multi Index
Boost Multi Index
 
Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASP
 
Dollar symbol
Dollar symbolDollar symbol
Dollar symbol
 
HadoopとMongoDBを活用したソーシャルアプリのログ解析
HadoopとMongoDBを活用したソーシャルアプリのログ解析HadoopとMongoDBを活用したソーシャルアプリのログ解析
HadoopとMongoDBを活用したソーシャルアプリのログ解析
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and Monitoring
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First Widget
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 

Viewers also liked

конференция нижний новгород (иэгос юркевич) 16 04 13
конференция нижний новгород (иэгос юркевич) 16 04 13конференция нижний новгород (иэгос юркевич) 16 04 13
конференция нижний новгород (иэгос юркевич) 16 04 13Victor Gridnev
 
2016 Infiniti Q70 Brochure | Infiniti Dealer in OC
2016 Infiniti Q70 Brochure | Infiniti Dealer in OC2016 Infiniti Q70 Brochure | Infiniti Dealer in OC
2016 Infiniti Q70 Brochure | Infiniti Dealer in OC
INFINITI Mission Viejo
 
WAP Man Dev Program Cert
WAP Man Dev Program CertWAP Man Dev Program Cert
WAP Man Dev Program CertAlan Proctor
 
Videojuegos favoritos
Videojuegos favoritosVideojuegos favoritos
Videojuegos favoritos
nicox8_rojas
 
TauckMariannaCorneliusProfessionalRefferal
TauckMariannaCorneliusProfessionalRefferalTauckMariannaCorneliusProfessionalRefferal
TauckMariannaCorneliusProfessionalRefferalBrandon Squires
 
Reference letter prof Kozlowski
Reference letter prof KozlowskiReference letter prof Kozlowski
Reference letter prof KozlowskiBernard Lis
 
20151220070135
2015122007013520151220070135
20151220070135MU Saad
 
Recommendation Letter DMBOS
Recommendation Letter DMBOSRecommendation Letter DMBOS
Recommendation Letter DMBOSBernard Lis
 
ЕСИА Reglament vzaimodeystviya v1.2
ЕСИА  Reglament vzaimodeystviya v1.2ЕСИА  Reglament vzaimodeystviya v1.2
ЕСИА Reglament vzaimodeystviya v1.2
Victor Gridnev
 
NdFeB Magnet- Euke MagTech Ltd
NdFeB Magnet- Euke MagTech Ltd NdFeB Magnet- Euke MagTech Ltd
NdFeB Magnet- Euke MagTech Ltd
Euke MagTech Limited
 
masters diploma authentic certificate
masters diploma authentic certificatemasters diploma authentic certificate
masters diploma authentic certificateFouad Zouein, Ph.D.
 
Протокол подкомиссии по ИТ от 1 октября 2014 года
Протокол подкомиссии по ИТ от 1 октября 2014 годаПротокол подкомиссии по ИТ от 1 октября 2014 года
Протокол подкомиссии по ИТ от 1 октября 2014 года
Victor Gridnev
 

Viewers also liked (20)

Balancete 04 13
Balancete 04 13Balancete 04 13
Balancete 04 13
 
Balancete 08 12
Balancete 08 12Balancete 08 12
Balancete 08 12
 
конференция нижний новгород (иэгос юркевич) 16 04 13
конференция нижний новгород (иэгос юркевич) 16 04 13конференция нижний новгород (иэгос юркевич) 16 04 13
конференция нижний новгород (иэгос юркевич) 16 04 13
 
NB07 60x80.
NB07 60x80.NB07 60x80.
NB07 60x80.
 
2016 Infiniti Q70 Brochure | Infiniti Dealer in OC
2016 Infiniti Q70 Brochure | Infiniti Dealer in OC2016 Infiniti Q70 Brochure | Infiniti Dealer in OC
2016 Infiniti Q70 Brochure | Infiniti Dealer in OC
 
WAP Man Dev Program Cert
WAP Man Dev Program CertWAP Man Dev Program Cert
WAP Man Dev Program Cert
 
OzonJulyAugust2005[1]
OzonJulyAugust2005[1]OzonJulyAugust2005[1]
OzonJulyAugust2005[1]
 
Videojuegos favoritos
Videojuegos favoritosVideojuegos favoritos
Videojuegos favoritos
 
TauckMariannaCorneliusProfessionalRefferal
TauckMariannaCorneliusProfessionalRefferalTauckMariannaCorneliusProfessionalRefferal
TauckMariannaCorneliusProfessionalRefferal
 
7
77
7
 
Reference letter prof Kozlowski
Reference letter prof KozlowskiReference letter prof Kozlowski
Reference letter prof Kozlowski
 
20151220070135
2015122007013520151220070135
20151220070135
 
Recommendation Letter DMBOS
Recommendation Letter DMBOSRecommendation Letter DMBOS
Recommendation Letter DMBOS
 
ЕСИА Reglament vzaimodeystviya v1.2
ЕСИА  Reglament vzaimodeystviya v1.2ЕСИА  Reglament vzaimodeystviya v1.2
ЕСИА Reglament vzaimodeystviya v1.2
 
NdFeB Magnet- Euke MagTech Ltd
NdFeB Magnet- Euke MagTech Ltd NdFeB Magnet- Euke MagTech Ltd
NdFeB Magnet- Euke MagTech Ltd
 
masters diploma authentic certificate
masters diploma authentic certificatemasters diploma authentic certificate
masters diploma authentic certificate
 
6
66
6
 
Proyecto de vida
Proyecto de vidaProyecto de vida
Proyecto de vida
 
GSM
GSMGSM
GSM
 
Протокол подкомиссии по ИТ от 1 октября 2014 года
Протокол подкомиссии по ИТ от 1 октября 2014 годаПротокол подкомиссии по ИТ от 1 октября 2014 года
Протокол подкомиссии по ИТ от 1 октября 2014 года
 

Similar to Возможности, особенности и проблемы AR::Relation

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
Rabble .
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Rabble .
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
Jens-Christian Fischer
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
Michael Mahlberg
 
Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子
Yasuko Ohba
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
wolframkriesing
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
Damien Seguy
 
Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008
Ulf Wendel
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
Giordano Scalzo
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Variables, expressions, standard types
 Variables, expressions, standard types  Variables, expressions, standard types
Variables, expressions, standard types
Rubizza
 
Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in RailsSandip Ransing
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
Dr Nic Williams
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
Ígor Bonadio
 
ActiveRecord vs Mongoid
ActiveRecord vs MongoidActiveRecord vs Mongoid
ActiveRecord vs Mongoid
Ivan Nemytchenko
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
Nate Abele
 
jQuery Anti-Patterns for Performance
jQuery Anti-Patterns for PerformancejQuery Anti-Patterns for Performance
jQuery Anti-Patterns for Performance
András Kovács
 

Similar to Возможности, особенности и проблемы AR::Relation (20)

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
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
 
Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Variables, expressions, standard types
 Variables, expressions, standard types  Variables, expressions, standard types
Variables, expressions, standard types
 
Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in Rails
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
ActiveRecord vs Mongoid
ActiveRecord vs MongoidActiveRecord vs Mongoid
ActiveRecord vs Mongoid
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
jQuery Anti-Patterns for Performance
jQuery Anti-Patterns for PerformancejQuery Anti-Patterns for Performance
jQuery Anti-Patterns for Performance
 

More from Александр Ежов

Кеширование данных в БД
Кеширование данных в БДКеширование данных в БД
Кеширование данных в БД
Александр Ежов
 
Борьба с багами: RailsClub на DevConf 2015
Борьба с багами: RailsClub на DevConf 2015Борьба с багами: RailsClub на DevConf 2015
Борьба с багами: RailsClub на DevConf 2015
Александр Ежов
 
Rails 5: awesome features and breaking changes
Rails 5: awesome features and breaking changesRails 5: awesome features and breaking changes
Rails 5: awesome features and breaking changes
Александр Ежов
 
Big Data и Ruby
Big Data и RubyBig Data и Ruby
Big Data и Ruby
Александр Ежов
 
Abstract machines for great good
Abstract machines for great goodAbstract machines for great good
Abstract machines for great good
Александр Ежов
 
Rubt on Rails: 1000 запросов в секунду
Rubt on Rails: 1000 запросов в секундуRubt on Rails: 1000 запросов в секунду
Rubt on Rails: 1000 запросов в секунду
Александр Ежов
 
Liquor, Liquid и другие безопасные языки разметки в RoR
Liquor, Liquid и другие безопасные языки разметки в RoRLiquor, Liquid и другие безопасные языки разметки в RoR
Liquor, Liquid и другие безопасные языки разметки в RoR
Александр Ежов
 
Vim or die
Vim or dieVim or die
Capistrano Rails
Capistrano RailsCapistrano Rails
Capistrano Rails
Александр Ежов
 
Умное кэширование в Rails
Умное кэширование в RailsУмное кэширование в Rails
Умное кэширование в Rails
Александр Ежов
 
Sphinx как база данных
Sphinx как база данныхSphinx как база данных
Sphinx как база данных
Александр Ежов
 
Emacs и Rails
Emacs и RailsEmacs и Rails
Антикризисная презентация
Антикризисная презентацияАнтикризисная презентация
Антикризисная презентация
Александр Ежов
 
Eventmachine: структура evented-приложений
Eventmachine: структура evented-приложенийEventmachine: структура evented-приложений
Eventmachine: структура evented-приложений
Александр Ежов
 
Дэдлоки
ДэдлокиДэдлоки
Обзорное сравнение серверов приложений для Rails
Обзорное сравнение серверов приложений для RailsОбзорное сравнение серверов приложений для Rails
Обзорное сравнение серверов приложений для Rails
Александр Ежов
 
Приложения в плагинах
Приложения в плагинахПриложения в плагинах
Приложения в плагинах
Александр Ежов
 
Использования PgQ и Londste в rails-приложении
Использования PgQ и Londste в rails-приложенииИспользования PgQ и Londste в rails-приложении
Использования PgQ и Londste в rails-приложении
Александр Ежов
 
Масштабирование в Rails
Масштабирование в RailsМасштабирование в Rails
Масштабирование в Rails
Александр Ежов
 
Интернационализация и локализация Ruby on Rails. gem russian
Интернационализация и локализация Ruby on Rails. gem russianИнтернационализация и локализация Ruby on Rails. gem russian
Интернационализация и локализация Ruby on Rails. gem russian
Александр Ежов
 

More from Александр Ежов (20)

Кеширование данных в БД
Кеширование данных в БДКеширование данных в БД
Кеширование данных в БД
 
Борьба с багами: RailsClub на DevConf 2015
Борьба с багами: RailsClub на DevConf 2015Борьба с багами: RailsClub на DevConf 2015
Борьба с багами: RailsClub на DevConf 2015
 
Rails 5: awesome features and breaking changes
Rails 5: awesome features and breaking changesRails 5: awesome features and breaking changes
Rails 5: awesome features and breaking changes
 
Big Data и Ruby
Big Data и RubyBig Data и Ruby
Big Data и Ruby
 
Abstract machines for great good
Abstract machines for great goodAbstract machines for great good
Abstract machines for great good
 
Rubt on Rails: 1000 запросов в секунду
Rubt on Rails: 1000 запросов в секундуRubt on Rails: 1000 запросов в секунду
Rubt on Rails: 1000 запросов в секунду
 
Liquor, Liquid и другие безопасные языки разметки в RoR
Liquor, Liquid и другие безопасные языки разметки в RoRLiquor, Liquid и другие безопасные языки разметки в RoR
Liquor, Liquid и другие безопасные языки разметки в RoR
 
Vim or die
Vim or dieVim or die
Vim or die
 
Capistrano Rails
Capistrano RailsCapistrano Rails
Capistrano Rails
 
Умное кэширование в Rails
Умное кэширование в RailsУмное кэширование в Rails
Умное кэширование в Rails
 
Sphinx как база данных
Sphinx как база данныхSphinx как база данных
Sphinx как база данных
 
Emacs и Rails
Emacs и RailsEmacs и Rails
Emacs и Rails
 
Антикризисная презентация
Антикризисная презентацияАнтикризисная презентация
Антикризисная презентация
 
Eventmachine: структура evented-приложений
Eventmachine: структура evented-приложенийEventmachine: структура evented-приложений
Eventmachine: структура evented-приложений
 
Дэдлоки
ДэдлокиДэдлоки
Дэдлоки
 
Обзорное сравнение серверов приложений для Rails
Обзорное сравнение серверов приложений для RailsОбзорное сравнение серверов приложений для Rails
Обзорное сравнение серверов приложений для Rails
 
Приложения в плагинах
Приложения в плагинахПриложения в плагинах
Приложения в плагинах
 
Использования PgQ и Londste в rails-приложении
Использования PgQ и Londste в rails-приложенииИспользования PgQ и Londste в rails-приложении
Использования PgQ и Londste в rails-приложении
 
Масштабирование в Rails
Масштабирование в RailsМасштабирование в Rails
Масштабирование в Rails
 
Интернационализация и локализация Ruby on Rails. gem russian
Интернационализация и локализация Ruby on Rails. gem russianИнтернационализация и локализация Ruby on Rails. gem russian
Интернационализация и локализация Ruby on Rails. gem russian
 

Recently uploaded

原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
u86oixdj
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
enxupq
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
slg6lamcq
 
The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...
jerlynmaetalle
 
Machine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptxMachine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptx
balafet
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
Oppotus
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
ewymefz
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
pchutichetpong
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
slg6lamcq
 
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
v3tuleee
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
Subhajit Sahu
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
John Andrews
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Subhajit Sahu
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
ahzuo
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
nscud
 
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project PresentationPredicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Boston Institute of Analytics
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
ArpitMalhotra16
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
ewymefz
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
ukgaet
 

Recently uploaded (20)

原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
 
The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...
 
Machine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptxMachine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptx
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
 
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
 
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project PresentationPredicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
 

Возможности, особенности и проблемы AR::Relation

  • 9. Not only Arel • Queries are not only Arel • AR ≠ Arel
  • 10. 3.x (x ≤1) • It’s not only Arel! AR::Relation was released • Identity Map (WHORRAAAA)
  • 11. ActiveRecord module ActiveRecord #:nodoc: class << self # Class methods delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped delegate :find_each, :find_in_batches, :to => :scoped delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped end end
  • 12. Scoped def scoped(options = nil) if options scoped.apply_finder_options(options) else if current_scope current_scope.clone else scope = relation.clone scope.default_scoped = true scope end end end
  • 13. Finder methods • where • having • select • order • limit • offset All finder methods work through AR::Relation • joins • includes • lock • readonly • from
  • 14. Example.Where def where(opts, *rest) return self if opts.blank? relation = clone relation.where_values += build_where(opts, rest) relation end
  • 15. ActiveRecord::Relation def to_a @records = if @readonly_value.nil? && !@klass.locking_enabled? eager_loading? ? find_with_associations : @klass.find_by_sql (arel.to_sql, @bind_values) else IdentityMap.without do eager_loading? ? find_with_associations : @klass.find_by_sql (arel.to_sql, @bind_values) end end end Real quering from the AR::Relation
  • 16. AR::Relation problems • merging default_scope’s with labmda (solved): default_scope where(:name => "qwerty") default_scope lambda { order("id DESC") } • except (I’ve wrote a patch): scope :xxx, order("id DESC") scope :yyy, except(:order).order("id ASC") @surveys = Survey.xxx.yyy Survey Load (0.1ms) SELECT "surveys".* FROM "surveys" ORDER BY id DESC, id ASC
  • 17. IdentityMap Identity map was written by Emilio Tagua
  • 19. Without IdentityMap user1 = User.find(1) # => #<User id: 1, name: "Josh"> user2 = User.find(1) # => #<User id: 1, name: "Josh"> user1 == user2 # => true, b/c AR::Base recognizes that # they have the same primary key user1.object_id == user2.object_id # => false, b/c these are two # different in-memory objects User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Code example from: http://edgerails.info/articles/what-s-new-in-edge-rails/2011/04/21/activerecord-identity- map/index.html
  • 20. With IdentityMap user1 = User.find(1) # => #<User id: 1, name: "Josh"> user2 = User.find(1) # => #<User id: 1, name: "Josh"> user1 == user2 # => true user1.object_id == user2.object_id # => true, b/c these really are # the same in-memory objects User Load (2.2ms) SELECT "users".* FROM "users" LIMIT 1 User with ID = 1 loaded from Identity Map Code example from: http://edgerails.info/articles/what-s-new-in-edge-rails/2011/04/21/activerecord-identity- map/index.html
  • 21. Even more... post = Post.find(1) same_post = post.comments.first.post post.object_id == same_post.object_id # => true Code example from: http://miloops.com/post/3391477665/identity-map-and-active-record
  • 22. Thread safe • Creates for each request • Uses Thread.current def repository Thread.current[:identity_map] ||= Hash.new { |h,k| h[k] = {} } end
  • 23. Interesting... def update @survey = Survey.find(params[:id]) @surveys = Survey.all if @survey.update_attributes(params[:survey]) redirect_to(@survey, :notice => 'Survey was successfully updated.') else render :action => "edit" end end def update @survey = Survey.find(params[:id]) if @survey.update_attributes(params[:survey]) redirect_to(@survey, :notice => 'Survey was successfully updated.') else @surveys = Survey.all render :action => "edit" end end
  • 24. How to use IdentityMap • It will be in Rails 3.1 • To enable write in your application.rb: config.active_record.identity_map = true