<html><head><meta http-equiv="Content-Type" content="text/html charset=iso-8859-1"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; ">ActiveRecord has a thing where you can pass an record into a condition and it automatically converts to the PK, using a method called something like 'to_param' (but can't remember the exact name.)<div><br></div><div>The net effect is you don't have to treat int ids different to objects:</div><div><br></div><div>> u = User.first</div><div>=> #<User id: 1></div><div>> User.where(:id.not_in => [ u ] ).to_sql</div><div><div>=> "SELECT `users`.* FROM `users` WHERE `users`.`id` NOT IN (1)"</div></div><div><br></div><div>(I'm using metawhere to get the :id.not_in syntax. Old 3.0 project.)</div><div><br></div><div>-ash</div><div><br><div><div>On 28 Feb 2013, at 11:41, Michael Pavling <<a href="mailto:pavling@gmail.com">pavling@gmail.com</a>> wrote:</div><br class="Apple-interchange-newline"><blockquote type="cite"><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> Foo.excluding(params[:foo_ids_to_exclude])</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>
_______________________________________________<br>Chat mailing list<br><a href="mailto:Chat@lists.lrug.org">Chat@lists.lrug.org</a><br>http://lists.lrug.org/listinfo.cgi/chat-lrug.org<br></blockquote></div><br></div></body></html>