All pastes #60507 Raw Edit

Miscellany

public text v1 · immutable
#60507 ·published 2006-06-01 03:39 UTC
rendered paste body
Use a left join with a has_many/belongs_to:

Instead of the standard rails way of one query per foreign key record. Say you have an author who has_many :books, and a book belongs_to :author (assume only 1 author per book for this example). Then you can do the following to preload all the books the author has written, when querying for the author

 @author = Author.find(params[:id], :include => :books) 


Properly substitute variables in an SQL Query

 @records = Record.find(:all, :conditions => ["author_id = ?", params[:author]])

 @records = Record.find(:all, :conditions => ["author_id = :author", params])