Rails Best Practices

14 votes

12236 views

Move finder to named_scope

Complex finders in controller make application hard to maintain. Move them into the model as named_scope can make the controller simple and the complex find logics are all in models.

implemented

Comments

by ihower
ihower

13 votes

20960 views

Use model association

Use model association to avoid assigning reference in controller.

implemented

Comments

by ihower
ihower

18 votes

13084 views

Use scope access

You can use scope access to avoid checking the permission by comparing the owner of object with current_user in controller.

implemented

Comments

by ihower
ihower

8 votes

24443 views

Add model virtual attribute

Do not assign the model's attributes directly in controller. Add model virtual attribute to move the assignment to model.

implemented

Comments

by ihower
ihower

3 votes

8638 views

Use model callback

Use model callback can avoid writing some logic codes in controller before or after creating, updating and destroying a model.

Comments

by ihower
ihower

9 votes

10552 views

Replace Complex Creation with Factory Method

Sometimes you will build a complex model with params, current_user and other logics in controller, but it makes your controller too big, you should move them into model with a factory method

implemented

Comments

by ihower
ihower

3 votes

16341 views

Move Model Logic into the Model

In MVC model, controller should be simple, the business logic is model's responsibility. So we should move logic from controller into the model.

implemented

Comments

by ihower
ihower

3 votes

7004 views

model.collection_model_ids (many-to-many)

When you want to associate a model to many association models by checkbox on view, you should take advantage of model.collection_model_ids to reduce the code in controller.

Comments

by ihower
ihower

6 votes

14610 views

Nested Model Forms

Use accepts_nested_attributes_for to make nested model forms much easier, this feature is provided by rails 2.3

Comments

by ihower
ihower

4 votes

7899 views

Overuse route customizations

According to Roy Fielding’s doctoral thesis, we should use restful routes to represent the resource and its state. Use the default 9 actions without overusing route customizations.

implemented

Comments

by ihower
ihower