[LRUG] Better idiom for this?
Ash Berlin
ash_lrug at firemirror.com
Thu Feb 28 03:56:10 PST 2013
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.)
The net effect is you don't have to treat int ids different to objects:
> u = User.first
=> #<User id: 1>
> User.where(:id.not_in => [ u ] ).to_sql
=> "SELECT `users`.* FROM `users` WHERE `users`.`id` NOT IN (1)"
(I'm using metawhere to get the :id.not_in syntax. Old 3.0 project.)
-ash
On 28 Feb 2013, at 11:41, Michael Pavling <pavling at gmail.com> wrote:
> 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
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20130228/2a5345d8/attachment-0003.html>
More information about the Chat
mailing list