[LRUG] Better idiom for this?
Michael Pavling
pavling at gmail.com
Thu Feb 28 03:41:17 PST 2013
Hiya,
Ruby (well... Rails) question...
I frequently have a need to return a collection of model objects, which
exclude some amount of records (by ID)
I want the flexibility to be able to do the exclusion on either instances
of the model, or just ids (as strings or integers).
I have previously used a named scope, and currently (3.2) have started to
use a class-method, but it's looking a little clunky/smelly to me...
class Foo < ActiveRecord::Base
class << self
def excluding(*objects)
objects = objects.flatten.delete_if(&:blank?)
object_ids = objects.map { |object| object.respond_to?(:to_i) ?
object.to_i : object.id }
object_ids.any? ? where(['id NOT IN (?)', object_ids]) : scoped
end
end
end
# so I can now call:
Foo.excluding(some_foo_object)
Foo.excluding(some_foo_object, another_foo_object)
Foo.excluding([1,2,3])
Foo.excluding(params[:foo_ids_to_exclude])
etc.
OOI does anyone have a better idiom for this approach?
M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20130228/6b8dc2f4/attachment-0003.html>
More information about the Chat
mailing list