6. SQL Injection
Prevent SQL injection by using ? to set the params of
the query
Bad Practice
Good Practice
7. 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)
8. Solution to N+1 queries
problem
Eager Loading
Use “includes”. With includes, ActiveRecord ensures that all of the
specified associations are loaded using minimum possible queries.
10. Use Query Attribute
Do you always check if ActiveRecord’s attributes exists
or are blank? present?
Rails provides a cleaner way by query attribute
Bad Practice
Good Practice
Each attribute of ActiveRecord’s model has a query
method, so you don’t need to use present? blank?
11. Annotate your models
Don’t go to schema.rb file everytime to find the table
structure information.
We have a easier way. Use gem annotate
https://github.com/ctran/annotate_models
It will automatically add comments at the top and
bottom of your models to list the table structures
information
13. Protect Mass Assignment
Problem :
Solution: You can use attr_protected to declare a blacklist of variables you
don’t want it to be assigned
14. DRY Code
Don’t repeat the code in controller. You can avoid that
using before_filter
Eg: Bad practice
15. Removing repeated code
As you saw in previous slide, below statement was
repeated in all actions. We can avoid it if we use before
filter
Good Practice