[LRUG] Better idiom for this?

Tom Stuart tom at codon.com
Thu Feb 28 03:56:32 PST 2013


On 28 Feb 2013, at 11:41, Michael Pavling wrote:
> 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).

AFAIK Active Record does this for you automatically, by using the connection adaptor to quote each model instance[1]:

>> Foo.where(['id NOT IN (?)', [Foo.first, Foo.find(2), 3, '4']]).to_sql
=> "SELECT \"foos\".* FROM \"foos\"  WHERE (id NOT IN (1,2,3,'4'))"

Whether this SQL is acceptable depends on your database, but it works fine on Postgres.

Cheers,
-Tom

[1] https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb#L9-L10


More information about the Chat mailing list