Collect an array of IDs from any object

Updated . Posted . Visible to the public.

The Edge Rider gem Show archive.org snapshot will define a method collect_ids on your ActiveRecord models, scopes, integer scalars and collections, which will return a list of their IDs:

User.last.collect_ids # => [9]
[User.first, User.last].collect_ids # => [1, 9]
User.active.collect_ids # => [4, 5, 6]
[4, 5, 6].collect_ids # => [4, 5, 6]
7.collect_ids #=> [7]

This allows you to parametrize scopes with a variety of argument types:

class Note < ActiveRecord::Base
  named_scope :for_users, lambda { |user_or_users| { :conditions => { :user_id => user_or_users.collect_ids }}}
end

# in another piece of code
Note.for_users(User.last) # => ActiveRecord::Scope
Note.for_users([User.first, User.last]) # => ActiveRecord::Scope
Note.for_users(User.active) # => ActiveRecord::Scope
Note.for_users([4, 5, 6]) # => ActiveRecord::Scope
Note.for_users(7) # => ActiveRecord::Scope
Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-04-15 10:10)