Find_by_sql

written by Dariush about 1 month ago

A question that came up in our recent brain storming dealt with how to run sql within the rails code if AR (active records) has limitation. In my research I found that most of the work should be performed with AR, however there is also the function of find_by_sql

http://ar.rubyonrails.com/classes/ActiveRecord/Base.html#M000345

find_by_sql(sql)

Works like find(:all), but requires a complete SQL string. Examples:

Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id" 
Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]

Post a comment

Options:

Size

Colors