Good-rails-habits

Best practices in Rails that I need to learn to make into habits. Probably not useful to anyone who doesn't have the exact same habits as me.

Download as .zip Download as .tar.gz View on GitHub

Good Rails Habits

Use only one dot.

@invoice.customer.address is bad. What if the app changes so that the customer has both a billing and a shipping address? Use the delegate method to wrap without clutter.

Ref: Rails AntiPatterns, P23

A model shouldn't know the implementation details of another model.

class Pet < ActiveRecord::Base
  has_many :toys

  def find_cute_toys
    self.toys.where(:cute => true)
  end

This isn't good because Pet shouldn't know that Toy has a binary 'cute' column. This should be moved to the Toy model. (This actually needs a better example because the find_cute_toys method makes more sense to be on the Toy model as a scope, even without the implementation detail issue.)

Ref: Rails AntiPatterns, P52

Don't forget that div_for is handy

No need to set custom id's when you can do <%= div_for %>

Don't forget to use an index to keep model data (such as emails or usernames) unique

class AddIndexToUsersEmail < ActiveRecord::Migration
  def change
    add_index :users, :email, unique: true
  end
end

Speed up Factory Girl tests by using unsecure passwords in test environment

config/environments/test.rb
ActiveModel::SecurePassword.min_cost = true