Rails Best Practices

29 votes

20097 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

13 votes

7431 views

Use caching !

Using the cache will speed up your application response time a lot. In fact, when people will request your pages, rails won't be requested, apache will serve the cached pages, thus double advantage : Faster pages response time Lower charge on your server

Comments

gdurelle

25 votes

34667 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

11 votes

9299 views

Move code into helper

According to MVC architecture, there should not be logic codes in view, in this practice, I will introduce you to move codes into helper.

implemented

Comments

by ihower
ihower

10 votes

9777 views

Move code into model

According to MVC architecture, there should not be logic codes in view, in this practice, I will introduce you to move codes into model.

implemented

Comments

by ihower
ihower

10 votes

8675 views

Move code into controller

According to MVC architecture, there should not be logic codes in view, in this practice, I will introduce you to move codes into controller.

implemented

Comments

by ihower
ihower

3 votes

6996 views

DRY Controller (and debate)

For CRUD resources, we always write the same 7 actions with duplicated codes. To avoid this, you can use inherited_resources plugin. But be careful, there is DRY controller debate!! (http://www.binarylogic.com/2009/10/06/discontinuing-resourcelogic/) 1. You lose intent and readability 2. Deviating from standards makes it harder to work with other programmers 3. Upgrading rails trouble

Comments

by ihower
ihower

-7 votes

116906 views

Use before_filter

Don't repeat yourself in controller, use before_filter to avoid duplicated codes.

implemented

Comments

by ihower
ihower

16 votes

30782 views

Always add DB index

Always add index for foreign key, columns that need to be sorted, lookup fields and columns that are used in a GROUP BY. This can improve the performance for sql query. If you're not sure which column need to index , I recommend to use http://github.com/eladmeidar/rails_indexes, which provide rake tasks to find missing indexes.

implemented

Comments

by ihower
ihower

11 votes

17361 views

Isolating Seed Data

Rails 2.3.4 provides db:seed task that is the best way to insert seed data for set up a new application.

implemented

Comments

by ihower
ihower