SlideShare a Scribd company logo
1 of 9
Download to read offline
Here, I am going to list out the common mistakes need to be avoided by many Ruby on Rails developers.
1. Database column Indexing
At the beginning of programming , mostly during writing migrations, we forget to add indexes , which
may or may not have any effect in initial stages of application, but will have drastic delay in fetching
records from the database as the table size increases.
2. ActiveRecord transaction for saving multiple object
Whenever saving multiple objects in a single request, always use ActiveRecord::Base::transaction
method to support atomicity. So, if any record has not saved the entire transaction, will get rolled back
and nothing will be saved into the database.
Always add indexes to the column being used for searching records.
Example:
ActiveRecord::Base.transaction do
@tasks.each do |task|
task.save!
end
end
3. Using delete_all instead of destroy_all
ActiveRecord::Base::delete_all or ActiveRecord::Base#delete method deletes the record(s) from the
database without firing any callback. So, This method must be used sensibly.
Where as ActiveRecord::Base::destroy_all or ActiveRecord::Base#destroy executes before_destroy and
after_destroy callbacks.
4. Using IN sub-queries
Relational Database supports different types of sub-queries. Unfortunately, one of them is a
performance disaster.
IN and NOT IN sub-queries.
Static array in these queries are fine, but when used sub-query inside, it reduces the performance and
also there are limitation on the number of elements in these queries depending on different databases.
Do Not use queries like IN or NOT IN
These queries must be written using EXISTS or NOT EXISTS predicates to avoid serious performance
issues.
Note: Oracle optimizes IN fairly well same as EXITS, So both can be used. But not the same case with
NOT IN vs NOT EXISTS. Better to use NOT EXISTS even on Oracle instead of NOT IN predicate.
5. Storing Session in database
It is very easy to store session data in relational databases, but it is the most expensive thing.
Session data are stored and retrieved more frequently and can create scenario when the database can
go unresponsive for the more important work to be done.
If there is a need of database for string session data, then use 'Memcache' or 'Redis'.
6. Set the primary key explicitly for database views
Sometimes we need to make use of database views for complex data joined from different tables, to
reduce the overheads of fetching data in a single query and also to support the searching and sorting
based on the columns of joined tables.
Always set the primary key explicitly in the respective model, this will provide the flexibility to define
association with other models.
Example:
Class UserDetailsView < ActiveRecord::Base
self.table_name = :user_details # user_details is a view in database
self.primary_key = :id # view_contains id from the joind user table and can be used as primary key for
this model
end
7. Use find_each
Do not use each method for iterating large set of records(ActiveRecord::Relation). It will fetch all the
record in a single query from the database and will dump into the memory, causing
performance degradation if the there is not enough memory. So, better make use of find_each method,
this method not only etches record in batches from the database but yields those once at a time too.
Once the current batch is processed another batch will be fetched from the database. So no need to
have all the records at once in the memory.
Example:
Book.where(:published => true).find_each do |book|
puts "Do something here!"
end
8. Make use of Ranges instead of comparisons for numbers
No more if x > 1000 &amp;&amp; x < 2000 nonsense. Instead:
year = 1972
case year
when 1970..1979: "Seventies"
when 1980..1989: "Eighties"
when 1990..1999: "Nineties"
end
9. Use pluck instead of map
We often need to find a single column from the database, So many of us make use of map method on
ActiveRecord::Relation.
Like:
User.active.select(:name).map(&:name)
Or, even worse:
User.active.map(&:name)
Instead use pluck method:
Example:
User.active.pluck(:name)
10. Allow both single item and and array to make use of the same loop without condition
I have observed that few folks write something like this
items.is_a?(Array) ? Items : [items]).each do |item|
#------------------
end
Instead use following:
[*items].each do |item|
#------------------
end
Above code will take care of items containing either a single object or array.
11. Rescue to the rescue
Use rescue for one liner statements which may throw error instead of condition:
hsh = {:age => 50}
hsh[:name].downcase #=> Error
hsh[:name].try(:downcase) #=> nil
Or, even worse:
hsh[:name] ? hsh[:name].downcase : nil #=> nil
Instead use as below:
hsh[:name].downcase rescue nil #=> nil
OR
hsh[:name].to_s.downcase #=> ''
12. Try to reduce redundancy using Ruby's logic
method for checking odd number:
def odd?(x)
x % 2 == 0 ? false : true
end
Instead make use of Ruby logics and simply it somewhat more.
def odd?(x)
x % 2 != 0
end
13. ActiveRecord::Base::exists
Sometime we just need to check for existence of any record in the database. And I have seen coders are
writing something like:
To check whether published books are present in the database or not:
books = Book.where(:published => true)
books.count > 0 # will return true if published books exists in database.
Instead use ActiveRecord::Base::exists method as:
Book.exists?(:published => true)
14. SQL Injection
Never interpolate the input from the outside world into ActiveRecord query directly.
query = "SELECT * FROM users WHERE name = '#{name}' AND password = '#{password'} LIMIT 1"
results = User.connection.execute(query)
Above query will behave unexpected whenever a sql injection string is passed and name nad password:
Example:
name: ' OR 'a' = 'a
password: ' OR 'a' = 'a
above input will generate query something like
SELECT * FROM users WHERE name = '' OR 'a' = 'a' AND password = '' OR 'a' = 'a' LIMIT 1
And above query will always return a user. Instead make use of 'where' or 'find_by' methods these will
automatically escape the commas('/”) in the input value and will not allow query to return true and will
check the record in database exactly what it had been passed as name and password.
15. N+1 queries
So, Basically it happens when we load a bunch of objects from the database, and then for each one of
those objects we make 1 or more database query.
Example:
class Customer { where(active: true) }
end
class Address < ActiveRecor...
belongs_to :customer
end
@customers = Customer.active
# this is fine the customer object is already in memory
# this one fires one query to the database for finding Address record for each custome
Suppose we have 100 active customers then total database queries will be 101.
1 query for finding all the active customers and other 100 queries for finding an address for each.
Instead try eager_loading and just fire 2 queries for all.
@customers = Customer.active.includes(:address)
The above query will fire 1 query for finding all the customers and other query for finding all the address
associated to the clients fetched in the first query.
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - Allerin

More Related Content

What's hot

Do something in 5 with gas 7-email log
Do something in 5 with gas 7-email logDo something in 5 with gas 7-email log
Do something in 5 with gas 7-email logBruce McPherson
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part IIFirdaus Adib
 
Two Many To Many Timber App
Two Many To Many Timber AppTwo Many To Many Timber App
Two Many To Many Timber AppAlexander Miller
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionBruce McPherson
 
Bristol 2009 q1_wright_steve
Bristol 2009 q1_wright_steveBristol 2009 q1_wright_steve
Bristol 2009 q1_wright_steveObsidian Software
 

What's hot (20)

Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Js objects
Js objectsJs objects
Js objects
 
Do something in 5 with gas 7-email log
Do something in 5 with gas 7-email logDo something in 5 with gas 7-email log
Do something in 5 with gas 7-email log
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
Underscore and Backbone Models
Underscore and Backbone ModelsUnderscore and Backbone Models
Underscore and Backbone Models
 
Two Many To Many Timber App
Two Many To Many Timber AppTwo Many To Many Timber App
Two Many To Many Timber App
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
ADO.NETObjects
ADO.NETObjectsADO.NETObjects
ADO.NETObjects
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Python database access
Python database accessPython database access
Python database access
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstraction
 
Bristol 2009 q1_wright_steve
Bristol 2009 q1_wright_steveBristol 2009 q1_wright_steve
Bristol 2009 q1_wright_steve
 
Lu solr32 34-20110912
Lu solr32 34-20110912Lu solr32 34-20110912
Lu solr32 34-20110912
 
 Mwa class custom_files
 Mwa class custom_files Mwa class custom_files
 Mwa class custom_files
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
 

Viewers also liked

Biosorption of hg (ii) from aqueous solutions using butea monosperma
Biosorption of hg (ii) from aqueous solutions using butea monospermaBiosorption of hg (ii) from aqueous solutions using butea monosperma
Biosorption of hg (ii) from aqueous solutions using butea monospermaeSAT Journals
 
B_Post_Recommendation1
B_Post_Recommendation1B_Post_Recommendation1
B_Post_Recommendation1Brian Post
 
Curriculum vitae of sawan mishra
Curriculum vitae of sawan mishraCurriculum vitae of sawan mishra
Curriculum vitae of sawan mishraSawan Mishra
 
Chaithanya resume ruby on rails
Chaithanya resume ruby on rails Chaithanya resume ruby on rails
Chaithanya resume ruby on rails Chaithanya A
 
CV-Kapranov-eng-2015
CV-Kapranov-eng-2015CV-Kapranov-eng-2015
CV-Kapranov-eng-2015Oleg Kapranov
 
Mid Senior Ruby on Rails developer zdalnie
Mid Senior Ruby on Rails developer zdalnieMid Senior Ruby on Rails developer zdalnie
Mid Senior Ruby on Rails developer zdalnieJoanna Ochocińska
 

Viewers also liked (13)

Biosorption of hg (ii) from aqueous solutions using butea monosperma
Biosorption of hg (ii) from aqueous solutions using butea monospermaBiosorption of hg (ii) from aqueous solutions using butea monosperma
Biosorption of hg (ii) from aqueous solutions using butea monosperma
 
abbie
abbieabbie
abbie
 
B_Post_Recommendation1
B_Post_Recommendation1B_Post_Recommendation1
B_Post_Recommendation1
 
bi
bibi
bi
 
Arpita Resume
Arpita ResumeArpita Resume
Arpita Resume
 
Rakesh - Java Resume
Rakesh - Java ResumeRakesh - Java Resume
Rakesh - Java Resume
 
CurriculumVitae
CurriculumVitaeCurriculumVitae
CurriculumVitae
 
Curriculum vitae of sawan mishra
Curriculum vitae of sawan mishraCurriculum vitae of sawan mishra
Curriculum vitae of sawan mishra
 
Arnold - Resume
Arnold - ResumeArnold - Resume
Arnold - Resume
 
MyResume
MyResumeMyResume
MyResume
 
Chaithanya resume ruby on rails
Chaithanya resume ruby on rails Chaithanya resume ruby on rails
Chaithanya resume ruby on rails
 
CV-Kapranov-eng-2015
CV-Kapranov-eng-2015CV-Kapranov-eng-2015
CV-Kapranov-eng-2015
 
Mid Senior Ruby on Rails developer zdalnie
Mid Senior Ruby on Rails developer zdalnieMid Senior Ruby on Rails developer zdalnie
Mid Senior Ruby on Rails developer zdalnie
 

Similar to Ruby on Rails Developer - Allerin

Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 
Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Servicevvatikiotis
 
OpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksOpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksJPC Hanson
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile appsIvano Malavolta
 
Perl and Elasticsearch
Perl and ElasticsearchPerl and Elasticsearch
Perl and ElasticsearchDean Hamstead
 
Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011rob_dimarco
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Odtug2011 adf developers make the database work for you
Odtug2011 adf developers make the database work for youOdtug2011 adf developers make the database work for you
Odtug2011 adf developers make the database work for youLuc Bors
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applicationsbrandonsavage
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning Arno Huetter
 
Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011bostonrb
 

Similar to Ruby on Rails Developer - Allerin (20)

Sequelize
SequelizeSequelize
Sequelize
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Service
 
OpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksOpenDMS - the first 2 weeks
OpenDMS - the first 2 weeks
 
MongoDB-presentation.pptx
MongoDB-presentation.pptxMongoDB-presentation.pptx
MongoDB-presentation.pptx
 
Oracle notes
Oracle notesOracle notes
Oracle notes
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Perl and Elasticsearch
Perl and ElasticsearchPerl and Elasticsearch
Perl and Elasticsearch
 
Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Odtug2011 adf developers make the database work for you
Odtug2011 adf developers make the database work for youOdtug2011 adf developers make the database work for you
Odtug2011 adf developers make the database work for you
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011
 

Recently uploaded

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 

Recently uploaded (20)

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 

Ruby on Rails Developer - Allerin

  • 1. Here, I am going to list out the common mistakes need to be avoided by many Ruby on Rails developers. 1. Database column Indexing At the beginning of programming , mostly during writing migrations, we forget to add indexes , which may or may not have any effect in initial stages of application, but will have drastic delay in fetching records from the database as the table size increases. 2. ActiveRecord transaction for saving multiple object Whenever saving multiple objects in a single request, always use ActiveRecord::Base::transaction method to support atomicity. So, if any record has not saved the entire transaction, will get rolled back and nothing will be saved into the database. Always add indexes to the column being used for searching records. Example: ActiveRecord::Base.transaction do @tasks.each do |task| task.save! end end 3. Using delete_all instead of destroy_all ActiveRecord::Base::delete_all or ActiveRecord::Base#delete method deletes the record(s) from the database without firing any callback. So, This method must be used sensibly. Where as ActiveRecord::Base::destroy_all or ActiveRecord::Base#destroy executes before_destroy and after_destroy callbacks.
  • 2. 4. Using IN sub-queries Relational Database supports different types of sub-queries. Unfortunately, one of them is a performance disaster. IN and NOT IN sub-queries. Static array in these queries are fine, but when used sub-query inside, it reduces the performance and also there are limitation on the number of elements in these queries depending on different databases. Do Not use queries like IN or NOT IN These queries must be written using EXISTS or NOT EXISTS predicates to avoid serious performance issues. Note: Oracle optimizes IN fairly well same as EXITS, So both can be used. But not the same case with NOT IN vs NOT EXISTS. Better to use NOT EXISTS even on Oracle instead of NOT IN predicate. 5. Storing Session in database It is very easy to store session data in relational databases, but it is the most expensive thing. Session data are stored and retrieved more frequently and can create scenario when the database can go unresponsive for the more important work to be done. If there is a need of database for string session data, then use 'Memcache' or 'Redis'. 6. Set the primary key explicitly for database views Sometimes we need to make use of database views for complex data joined from different tables, to reduce the overheads of fetching data in a single query and also to support the searching and sorting based on the columns of joined tables.
  • 3. Always set the primary key explicitly in the respective model, this will provide the flexibility to define association with other models. Example: Class UserDetailsView < ActiveRecord::Base self.table_name = :user_details # user_details is a view in database self.primary_key = :id # view_contains id from the joind user table and can be used as primary key for this model end 7. Use find_each Do not use each method for iterating large set of records(ActiveRecord::Relation). It will fetch all the record in a single query from the database and will dump into the memory, causing performance degradation if the there is not enough memory. So, better make use of find_each method, this method not only etches record in batches from the database but yields those once at a time too. Once the current batch is processed another batch will be fetched from the database. So no need to have all the records at once in the memory. Example: Book.where(:published => true).find_each do |book| puts "Do something here!" end 8. Make use of Ranges instead of comparisons for numbers No more if x > 1000 &amp;&amp; x < 2000 nonsense. Instead: year = 1972 case year when 1970..1979: "Seventies" when 1980..1989: "Eighties"
  • 4. when 1990..1999: "Nineties" end 9. Use pluck instead of map We often need to find a single column from the database, So many of us make use of map method on ActiveRecord::Relation. Like: User.active.select(:name).map(&:name) Or, even worse: User.active.map(&:name) Instead use pluck method: Example: User.active.pluck(:name) 10. Allow both single item and and array to make use of the same loop without condition I have observed that few folks write something like this items.is_a?(Array) ? Items : [items]).each do |item| #------------------ end Instead use following: [*items].each do |item| #------------------ end Above code will take care of items containing either a single object or array.
  • 5. 11. Rescue to the rescue Use rescue for one liner statements which may throw error instead of condition: hsh = {:age => 50} hsh[:name].downcase #=> Error hsh[:name].try(:downcase) #=> nil Or, even worse: hsh[:name] ? hsh[:name].downcase : nil #=> nil Instead use as below: hsh[:name].downcase rescue nil #=> nil OR hsh[:name].to_s.downcase #=> '' 12. Try to reduce redundancy using Ruby's logic method for checking odd number: def odd?(x) x % 2 == 0 ? false : true end Instead make use of Ruby logics and simply it somewhat more. def odd?(x) x % 2 != 0 end 13. ActiveRecord::Base::exists Sometime we just need to check for existence of any record in the database. And I have seen coders are writing something like: To check whether published books are present in the database or not:
  • 6. books = Book.where(:published => true) books.count > 0 # will return true if published books exists in database. Instead use ActiveRecord::Base::exists method as: Book.exists?(:published => true) 14. SQL Injection Never interpolate the input from the outside world into ActiveRecord query directly. query = "SELECT * FROM users WHERE name = '#{name}' AND password = '#{password'} LIMIT 1" results = User.connection.execute(query) Above query will behave unexpected whenever a sql injection string is passed and name nad password: Example: name: ' OR 'a' = 'a password: ' OR 'a' = 'a above input will generate query something like SELECT * FROM users WHERE name = '' OR 'a' = 'a' AND password = '' OR 'a' = 'a' LIMIT 1 And above query will always return a user. Instead make use of 'where' or 'find_by' methods these will automatically escape the commas('/”) in the input value and will not allow query to return true and will check the record in database exactly what it had been passed as name and password. 15. N+1 queries So, Basically it happens when we load a bunch of objects from the database, and then for each one of those objects we make 1 or more database query. Example: class Customer { where(active: true) } end class Address < ActiveRecor...
  • 7. belongs_to :customer end @customers = Customer.active # this is fine the customer object is already in memory # this one fires one query to the database for finding Address record for each custome Suppose we have 100 active customers then total database queries will be 101. 1 query for finding all the active customers and other 100 queries for finding an address for each. Instead try eager_loading and just fire 2 queries for all. @customers = Customer.active.includes(:address) The above query will fire 1 query for finding all the customers and other query for finding all the address associated to the clients fetched in the first query.