Improve your ActiveRecord performance

The case for piggy backed attributes

Improve your ActiveRecord performance via:

:include

def show_some
  @recipes = Recipe.find(:all, :limit => 50, :include => [:user])
end

piggy backed attributes

# model
class Recipe < ActiveRecord::Base
  belongs_to :user
  def user_name
    @attributes['user_name']
  end
end

# view
<% for r in @recipes %>
  <%= r.title %>, <%= r.user_name %>
  <br>
<% end %>

# controller
Recipe.find(:all, :limit => 50,
            :conditions => "r.user_id=u.id",
            :joins => 'r, users u',
            :select => 'r.*, u.name AS user_name')

SQL view

...create a SQL view that does the join and build a model against that view...(do not forget we have already views in MySQL 5.0 ;) )