Prevent SQL injection by using ? to set the params of
N + 1 queries problem
Consider the following code which finds 10 clients and prints their postcodes
Total queries executed here are 11. 1 to fine 10clients and then 10(1
per each client to find its address)
Solution to N+1 queries
Use “includes”. With includes, ActiveRecord ensures that all of the
specified associations are loaded using minimum possible queries.
Use Query Attribute
Do you always check if ActiveRecord’s attributes exists
or are blank? present?
Rails provides a cleaner way by query attribute
Each attribute of ActiveRecord’s model has a query
method, so you don’t need to use present? blank?
Annotate your models
Don’t go to schema.rb file everytime to find the table
We have a easier way. Use gem annotate
It will automatically add comments at the top and
bottom of your models to list the table structures
Use model association
Protect Mass Assignment
Solution: You can use attr_protected to declare a blacklist of variables you
don’t want it to be assigned
Don’t repeat the code in controller. You can avoid that
Eg: Bad practice
Removing repeated code
As you saw in previous slide, below statement was
repeated in all actions. We can avoid it if we use before
Gem for code metric tool for rails-projects
Online service to find security issues in rails project
Want to join our team.
Email your CV at
Want to hire us.
Contact us on