The Rails Way: Jamis Buck and Michael Kosiarski

Posted by patjoyce
May 20, 2007

The Rails Way

Goal is to describe the code style of rails through some examples.

Skinny Controller Fat Modeler

Common anti pattern is a fat controller. Difficult to test. Common newbie mistake is to equate model with DB table. A model can be anything that encapsulates your data. It doesn’t have to have anything to do with the DB. One benefit of splitting things out are that you can now easily test independently from your controller. Also you can now use the form builder helpers that rails provides.

with_scope antipattern

before_create hook naming

Don’t depend on naming hook methods before_create etc. that is a readability issue. give the method a meaningful name and then use the before_create class method to hook it up.

Association proxies

Code at the level of thought, not DB. example: @john.documents instead of Document.find_all_by_user_id(@john.id)

Apart from the readability benefit there are performance gain because subsequent calls in the same request won’t have to hit the DB.

Routes file

Use map.with_options to reduce documentation.

Comments

Leave a response

  1. Sean December 09, 2007 @ 08:48 PM

    Url is wrong http://www.therailsway.com/ is http://www.thereailsway.com/

  2. Patrick Joyce December 19, 2007 @ 04:31 PM

    Thanks for the note Sean, I fixed the link.

    Typos are a risk you run when live blogging an event. My copy editor mother was appalled at my spelling and grammatical errors.

Comment