[LRUG] Better idiom for this?

Oto Brglez otobrglez at gmail.com
Thu Feb 28 04:05:22 PST 2013


Hi! 

I would recommend creating scope with a little lambda... Like so:

scope :exclude, ->(who=nil) {
  User.where(["id NOT IN (?)", who.is_a?(Array) ? who.compact : who]) if who.present?
}


And you can use it like:

User.exclude
User.exclude 10
User.exclude [10,12]
User.exclude [nil,10,nil]
User.exclude User.first

Or even:

User.where(first_name: "Oto").exclude(9)

-- 
Oto Brglez

W: http://opalab.com
M: 0038631593799


On Thursday, February 28, 2013 at 12:41 PM, Michael Pavling 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 (http://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 (mailto: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/6a4d3580/attachment-0003.html>


More information about the Chat mailing list