2. Null Object Pattern # controller def current_user @current_user ||= User.find_by(id: user_id) || GuestUser.new end # model class GuestUser def name "Anonymous user" end end # view <%= current_user.name %>
3. Do Not Make Demeter Sad class Comment < ActiveRecord::Base belongs_to :author delegate :name, to: :author, prefix: true, allow_nil: true end class Comment < ActiveRecord::Base belongs_to :author def author_name author && author.name || "Anonymous" end end comment.author_name
5. Use proper database constraints class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.integer :author_id, null: false t.text :content, null: false t.timestamps end add_foreign_key :comments, :authors end end