May 16, 2011
RailsConf 2011: Rails Best Practices
This afternoon I'm at RailsConf 2011 listening to a bunch of the Envy Labs guys talk about best practices in rails. Excited for this tutorial because I've used rails long enough now that there's a bunch more to know than just the syntax. There are many ways to do things, want to get some direction on how rails does it.
The better title is Rails Best Opinions. This is a lab, so we listen to a presentation and see some slides and then get on our computers and implement the ideas in code.
A few things that caught my eye, as time permitted to jot down.
- Use scopes and default scope in the model to simplify controller logic, use a lambda for scoping where variables need to be re-evaluated.
- Use unscoped to override default scope.
- Envy Labs are coding things now where instance variables are always defined in the action (not in some helper method or down in another method where they aren't visible).
- Envy Labs are also parameters should not be used outside of the action, pass parameters to functions as arguments.
- Nested attributes simplifies code quite a bit.
- Use app presenters, not for HTML but bringing together a bunch of objects.
- use ActiveSupport::Memoizable for storing values to be retrieved more than one time.
- use responds_to() and responds_with() to simplify responding to different data formats.
- Add indexes, use something like new relic to see where there are performance issues in the app.
- Protect attributes with attr_accessible.
- use database defaults instead of in the code.
- Implement proper use of callbacks (after_create).
- Use rails date helpers.
- Improve validation with validate method for ActiveRecord::Base object, create class ActiveRecord::EachValidator to automatically run validation across many objects.
- Add errors to model with self.errors.add.
- Use db/seeds.db to put data in database, not in your migration scripts.
- Use the bullet gem, a great tool to tell you where your queries are N+1.
- When using the pluralize function, but be sure it scales to get the count of items.
- Use counter_cache technique to reduce queries when checking counts of related records.
For me, having worked heavily in Rails for the past month, the labs were a prefect stretch. Understandable, but challenging to work through the exercises.
Posted by mike at May 16, 2011 12:37 PM