<div>
Hi!
</div><div><br></div><div>I would recommend creating scope with a little lambda... Like so:</div><div><br></div><div><div>scope :exclude, ->(who=nil) {</div><div> User.where(["id NOT IN (?)", who.is_a?(Array) ? who.compact : who]) if who.present?</div><div>}</div></div>
<div><div><br></div><div>And you can use it like:</div><div><br></div><div>User.exclude</div><div>User.exclude 10</div><div>User.exclude [10,12]</div><div>User.exclude [nil,10,nil]</div><div>User.exclude User.first</div><div><br></div><div>Or even:</div><div><br></div><div>User.where(first_name: "Oto").exclude(9)</div><div><br></div><div>-- </div><div>Oto Brglez</div><div><br></div><div>W: http://opalab.com</div><div>M: 0038631593799</div><div><br></div></div>
<p style="color: #A0A0A8;">On Thursday, February 28, 2013 at 12:41 PM, Michael Pavling wrote:</p>
<blockquote type="cite" style="border-left-style:solid;border-width:1px;margin-left:0px;padding-left:10px;">
<span><div><div><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>
</div><div><div>_______________________________________________</div><div>Chat mailing list</div><div><a href="mailto:Chat@lists.lrug.org">Chat@lists.lrug.org</a></div><div><a href="http://lists.lrug.org/listinfo.cgi/chat-lrug.org">http://lists.lrug.org/listinfo.cgi/chat-lrug.org</a></div></div></div></span>
</blockquote>
<div>
<br>
</div>