where condition with array

59 views
Skip to first unread message

Soichi Ishida

unread,
Feb 24, 2013, 9:10:46 PM2/24/13
to rubyonra...@googlegroups.com
Rails 3.2.11


Say, my app needs special conditions like


plans = Plan.arel_table
@plan = Plan.where(
plans[:user_id].not_eq(3)
).where(
plans[:user_id].not_eq(4)
).where(
plans[:user_id].not_eq(7)
)...

If many not_eq conditions are needed, the way written like this is
inefficient.

Is there anyway to write this in a more concise way?

soichi

--
Posted via http://www.ruby-forum.com/.

Javier Quarite

unread,
Feb 24, 2013, 9:43:48 PM2/24/13
to rubyonra...@googlegroups.com

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 

I'm still analyzing it but it taught me a lot

Javier

tamouse mailing lists

unread,
Feb 25, 2013, 12:28:52 AM2/25/13
to rubyonra...@googlegroups.com
If going the SQL route, easier might be:

Plan.where("user_id not in (3,4,7)")

Soichi Ishida

unread,
Feb 25, 2013, 1:23:40 AM2/25/13
to rubyonra...@googlegroups.com
thanks. I haven't done sql query at all but this time I did for the
first time.

Bruno Santos

unread,
Feb 25, 2013, 10:23:48 PM2/25/13
to rubyonra...@googlegroups.com
Try something like this:

Plan.where("user_id not in (#{[3,4,7].join(', ')})")



2013/2/25 tamouse mailing lists <tamous...@gmail.com>

--
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 rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



Matt Jones

unread,
Feb 26, 2013, 3:42:03 PM2/26/13
to rubyonra...@googlegroups.com


On Monday, 25 February 2013 22:23:48 UTC-5, Bruno Santos wrote:
Try something like this:

Plan.where("user_id not in (#{[3,4,7].join(', ')})")


This easier, and won't risk SQL injection if that array has user-generated content:

Plan.where('user_id NOT IN ?', [3,4,7])

--Matt Jones
 

tamouse mailing lists

unread,
Feb 26, 2013, 11:51:10 PM2/26/13
to rubyonra...@googlegroups.com
On Tue, Feb 26, 2013 at 2:42 PM, Matt Jones <al2...@gmail.com> wrote:
> Plan.where('user_id NOT IN ?', [3,4,7])

Slight correction:

Plan.where('user_id NOT IN (?)', [3,4,7])
Reply all
Reply to author
Forward
0 new messages