<div dir="ltr">Hiya,<div><br></div><div style>Ruby (well... Rails) question...</div><div style><br></div><div style>I frequently have a need to return a collection of model objects, which exclude some amount of records (by ID)</div>
<div style><br></div><div style>I want the flexibility to be able to do the exclusion on either instances of the model, or just ids (as strings or integers).</div><div style><br></div><div style>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... </div>
<div style><br></div><div style><div> class Foo < ActiveRecord::Base</div><div> class << self<br></div><div> def excluding(*objects)</div><div> objects = objects.flatten.delete_if(&:blank?)</div>
<div> object_ids = objects.map { |object| object.respond_to?(:to_i) ? object.to_i : <a href="http://object.id">object.id</a> }</div><div> object_ids.any? ? where(['id NOT IN (?)', object_ids]) : scoped</div>
<div> end</div><div> end</div><div style> end</div><div style><br></div><div style> # so I can now call:</div><div style> Foo.excluding(some_foo_object)</div><div style> Foo.excluding(some_foo_object, another_foo_object)</div>
<div style><div> Foo.excluding([1,2,3])</div><div><div> Foo.excluding(params[:foo_ids_to_exclude])</div></div><div style> etc.</div><div style><br></div><div>OOI does anyone have a better idiom for this approach?<br></div>
<div><br></div><div style>M</div><div style><br></div></div></div></div>