Friday, September 17, 2010

:select, joins, where parameters in ActiveRecord find of rails

Extracting distinct records from a table can be done using

@players = Player.find(:all).map{ |player| player.name }.uniq

Here it queries and gets all the records from the table and a ruby method is executed to get the distinct records which makes it a bad solution as far as performance is concerned.

A better way to do this is to use the :select parameter of the ActiveRecord find method

@players = Player.find(:all, :select => 'DISTINCT name')

few other examples of using :select

@players = Player.find(:all, :select => ‘name, sur_name, date_of_birth’)

instead of @players = Player.find(:all) if the table data is huge.
However Player.find(:all) will be faster for short lists because of the Rails cache.

Player.find( :all,
:select => Player.column_names.select {|col| col != "sur_name"})

Using "where" for join tables
@users = User.joins(:roles).where(:roles => { :name => [Role::ADMIN, Role::CLIENT_ADMIN]})