finder_options.rb

Path: ar-extensions/lib/ar-extensions/finder_options.rb
Last Update: Mon Apr 13 03:13:49 -0600 2009

ActiveRecord::Extensions::FinderOptions provides additional functionality to the ActiveRecord ORM library created by DHH for Rails.

Using finder_sql_to_string

Expose the finder sql to a string. The options are identical to those accepted by find(:all, options) the find method takes.

Example:

  sql = Contact.finder_sql_to_string(:include => :primary_email_address)
  Contact.find_by_sql(sql + 'USE_INDEX(blah)')

Enhanced Finder Options

Add index hints, keywords, and pre and post SQL to the query without writing direct SQL

Parameter options:

  • :pre_sql appends SQL after the SELECT and before the selected columns
 sql = Contact.find :first, :pre_sql => "HIGH_PRIORITY", :select => 'contacts.name', :conditions => 'id = 5'
 SQL> SELECT HIGH_PRIORITY contacts.name FROM `contacts` WHERE id = 5
  • :post_sql appends additional SQL to the end of the statement
 Contact.find :first, :post_sql => 'FOR UPDATE', :select => 'contacts.name', :conditions => 'id = 5'
 SQL> SELECT contacts.name FROM `contacts` where id == 5 FOR UPDATE

 Book.find :all, :post_sql => 'USE_INDEX(blah)'
 SQL> SELECT books.* FROM `books` USE_INDEX(blah)
  • :override_select is used to override the SELECT clause of eager loaded associations

The :select option is ignored by the vanilla ActiveRecord when using eager loading with associations (when :include is used) (refer to dev.rubyonrails.org/ticket/5371) The :override_select options allows us to directly specify a SELECT clause without affecting the operations of legacy code (ignore :select) of the current code. Several plugins are available that enable select with eager loading Several plugins exist to force :select to work with eager loading. script/plugin install git://github.com/blythedunham/eload-select.git

  • :having only works when :group option is specified
 Book.find(:all, :select => 'count(*) as count_all, topic_id', :group => :topic_id, :having => 'count(*) > 1')
 SQL>SELECT count(*) as count_all, topic_id FROM `books`  GROUP BY topic_id HAVING count(*) > 1

Developers

Homepage

Required files

active_record/version  

[Validate]