active_record_helpers plugin provides a bunch of helpful methods.

Class Methods

ids(field = “id”)

Returns an array of the values of field converted to Integer

>> Deathmatch.finished.recent.ids
=> [505, 501, 500]
>> Deathmatch.finished.recent.ids(:map_id)
=> [4, 4, 6]

attribute(field)

Returns an array of the field’s raw values

>> Player.scoped(:limit => 3, :order => 'rating desc').attribute(:name)
=> ["boffy", "pitibo", "macovsky"]

attributes(fields)

Returns an array of record hashes with the column names as keys and column raw values as values

>> Deathmatch.finished.last.players.scoped(:limit => 3, :order => 'frags desc').attributes(:name, :frags)
=> [{"name" => "boffy", :frags => "35"}, {"name" => "pitibo", "frags" => "34"}, {"name" => "macovsky", "frags" => "33"}]

All of these methods work fast because they don’t instantiate ActiveRecord objects.

They were originally made by Max Lapshin — github.com/maxlapshin

update_all_counters

Works as update_counters, but accepts the same arguments as update_all method. Consider examples:

Flow.update_all_counters({:rating => 1}, {:id => 3})
Flow.update_all_counters({:rating => 1, :votes_left => -1}, ["user_id=?", 3])
Post.update_all_counters({:rating => 1}, :order => "created_at", :limit => 100)

select_fields

Returns SQL-text for passing to :select option in finder

>> Player.select_fields(%w{id name frags})
=> "players.id, players.title, players.permalink" 
>> Deathmatch.select_fields('id', 'players.name as winner_name')
=> "deathmatches.id, players.name as winner_name"

Instance Methods

to_poly_params

Returns a hash for polymorphic conditions

>> User.first.to_poly_params
=> {:resource_type=>"User", :resource_id=>3}
>> User.first.to_poly_params('post')
=> {:post_id=>3, :post_type=>"User"}

Object#get_id

It also adds a get_id method to Object useful in methods which can receive either an ActiveRecord instance or its id.

>> User.last.get_id
=> 5
>> 5.get_id
=> 5

Installation

script/plugin install git://github.com/robotector/active_record_helpers.git