You can always use the underlying arel_table:
Plan.where(arel_table[:user_id].not_eq([3,4,7]))
Saving off what the user_ids of [3,4,7] mean might make it a bit clearer
too:
declarative_name = arel_table[:user_id].not_eq(ids)
Plane.where(declarative_name)
Or succinctly in a scope:
scope :declarative_name, ->(ids) { where(arel_table[:user_id].not_eq(ids)) }
# => Plan.declarative_name [3,4,7]
There is a railscast for promoting the Arel predicates to class level
methods on active_record objects:
http://railscasts.com/episodes/355-hacking-with-arel
So you could end up with:
Plan.match(user_id: { not_in: [3,4,7] })
The draw back is that your interface for all active_record objects is more
expansive, but it depends on the style of the app and your preferences on
this matter, I like to keep a minimal public interface personally.
And finally the squeel gem <https://github.com/ernie/squeel> sprung to mind
which automagically adds these predicates to active_record objects too:
Plan.where{ user_id.not_in [3,4,7] }
I've tried all of these approaches except the railscast version, and like
access the arel_table directly to build queries the best, as you learn more
that way :-)
On Tuesday, 26 February 2013 03:23:48 UTC, Bruno Santos wrote:
>
> Try something like this:
>
> Plan.where("user_id not in (#{[3,4,7].join(', ')})")
>
>
>
> 2013/2/25 tamouse mailing lists <[email protected] <javascript:>>
>
>> On Sun, Feb 24, 2013 at 8:43 PM, Javier Quarite
>> <[email protected]<javascript:>>
>> wrote:
>> >
>> > Have you considered doing a sql query?
>> >
>> > my approach would be this
>> >
>> > query_array = []
>> > [3,4,7].each do |value|
>> > query_array << "user_id != #{value}"
>> > end
>> >
>> > Plan.where("#{query_array}.join(" and ")")
>> >
>> > Also, the past week I found this gist from ryan
>> > https://gist.github.com/ryanb/4974414
>> >
>> > I'm still analyzing it but it taught me a lot
>> >
>> > Javier
>>
>> If going the SQL route, easier might be:
>>
>> Plan.where("user_id not in (3,4,7)")
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Ruby on Rails: Talk" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to [email protected] <javascript:>.
>> To post to this group, send email to
>> [email protected]<javascript:>
>> .
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msg/rubyonrails-talk/-/0fsT1g5jZSoJ.
For more options, visit https://groups.google.com/groups/opt_out.