Rails Best Practices

37 votes

8306 views

Double-check your migrations

When you generate a new migration, try it forwards and backwards to ensure it has no errors

Comments

jaimeiniesta

35 votes

37367 views

Use memoization

Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs. In rails, you can easily use memoize which is inherited from ActiveSupport::Memoizable.

Comments

flyerhzm

34 votes

29826 views

Use Observer

Observer serves as a connection point between models and some other subsystem whose functionality is used by some of other classes, such as email notification. It is loose coupling in contract with model callback.

implemented

Comments

by ihower
ihower

32 votes

22198 views

split route namespaces into different files

the routes will become complicated with the growth of your application, contain different namespaces, each with a lot of resources and custom routes, it would be better to split routes into different files according to the namespaces, which makes it easy to maintain the complicated routes.

Comments

flyerhzm

29 votes

20517 views

Fix N+1 Queries

N+1 Queries is a serious database performance problem. Be careful of that situation! If you're not sure, I recommend you install http://github.com/flyerhzm/bullet plugin, which helps you reduce the number of queries with alerts (and growl).

Comments

by ihower
ihower

27 votes

29850 views

Annotate your models

Are you tired of going to schema.rb to find your table structures information? It would be better to list all the attributes of the model in the model itself.

Comments

flyerhzm

27 votes

30829 views

Not use time_ago_in_words

It's very common for a rails developer to use time_ago_in_words to display time like "5 minutes ago", but it's too expensive to calculate the time in server side, you should utilize client cpu to calculate the time ago.

implemented

Comments

flyerhzm

25 votes

35604 views

Replace instance variable with local variable

In partial view, we can use the instance variable directly, but it may be confused and make it hard to reuse anywhere, because we don't know exactly which instance variable can be used, so use the local variable in partial with explicitly assignment.

implemented

Comments

by ihower
ihower

23 votes

26946 views

the Law of Demeter

According to the law of demeter, a model should only talk to its immediate association, don't talk to the association's association and association's property, it is a case of loose coupling.

implemented

Comments

by ihower
ihower

22 votes

20099 views

Use query attribute

Do you always check if ActiveRecord's attributes exist or not by nil?, blank? or present? ? Don't do that again, rails provides a cleaner way by query attribute

implemented

Comments

flyerhzm