Read more

Collect an array of IDs from any object

Henning Koch
April 15, 2011Software engineer at makandra GmbH

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]
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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
Posted by Henning Koch to makandra dev (2011-04-15 12:10)