Forum: Ruby on Rails How to do IN(?) query?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Richard L. (Guest)
on 2006-04-06 00:05
(Received via mailing list)
I'm trying to do an IN query, where I have an array of user objects
imaginatively named 'users':

:conditions=>["user_id IN (?)", users.collect{|u| }.join(',')]

this ends up with:

... IN('1,2,3') ...

Obviously I want this to be:

... IN(1,2,3) ...
or even
... IN('1', '2', '3') ...

How do I get ActiveRecord to stop quoting the whole thing?

I thought passing in the object array itself did the trick - the
documentation says as such, giving the following example:

Person.find(:all, :conditions => [ "category IN (?)", categories])

When I try this, the array is printed and my query looks something like:

IN ('--- !ruby/object:User \nattributes: .....

Any ideas?

Thanks in advance - I'll carry on Googling and see what I can turn up!
zdennis (Guest)
on 2006-04-06 00:39
(Received via mailing list)
If categories is an array of numbers (think user id's) your second idea
will work:

  users = [ 1,2,3,4,5]
  Person.find :all, :conditions=>['id IN (?)', users]

but since you have actual user objects you could simplify and say:

  users = [ user1, user2, user3 ]
  Person.find_all_by_id{ |u| }

Hope this helps,

Richard L. (Guest)
on 2006-04-06 01:06
(Received via mailing list)
Superb - thanks!

Just had to take out the .join(',') and all works a charm.

Thanks again.

Jonathan V. (Guest)
on 2006-04-06 03:23
(Received via mailing list)
You can also use a handy rails shortcut:

categories.collect { |c| }

Can be written as:


Tobias Lütke (Guest)
on 2006-04-06 03:24
(Received via mailing list)

On 4/5/06, Richard L. <removed_email_address@domain.invalid> wrote:
> _______________________________________________
> Rails mailing list
> removed_email_address@domain.invalid

Tobi       - modern e-commerce software - Open source weblog engine - Technical weblog
This topic is locked and can not be replied to.