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