Posted over 9 years ago. Visible to the public.

Collect an array of IDs from any object

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

Copy
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:

Copy
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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Henning Koch
Last edit:
over 7 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more