[LRUG] Better idiom for this?

Paul Battley pbattley at gmail.com
Thu Feb 28 04:26:55 PST 2013


On 28 February 2013 12:13, James Almond <james at jamesalmond.com> wrote:
> One thing worth noting about this syntax is that with postgres (and possibly others)
>
> Foo.where(['id NOT IN (?)', [])
> => SELECT "foo".* FROM "foo" WHERE (id NOT in (NULL))
>
> which returns no rows at all. So something like Foo.excluding([]) wouldn't have the expected outcome in my opinion. I would expect it to be "Foo excluding nothing" when it actually returns "Foo excluding everything"

Yes. This is really confusing. What I've done is just to append [0] to
the ID array: IDs start at 1, and it's simpler than testing and
branching (as in Oto's solution):

    scope :exclude, lambda { |ids| where(arel_table[:id].not_in(ids + [0])) }

Oh, and whatever you do, DON'T call the scope "except". You'll waste
half a day wondering why composing scopes doesn't work as it ought.

Paul.



More information about the Chat mailing list