Forum: Ruby on Rails query for multiple possible values of a field

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.
Naija G. (Guest)
on 2009-02-20 21:58

While browsing the above page, I looked at this query and wondered if it
could be changed to include multiple possible values for state:

find(:all, :origin => @somewhere, :within => 5,

How would I tell ActiveRecord to return any records where state was 'CA'
or 'TX' or 'NY'?  It seems like it'd be more efficient to go ahead and
constrain the results from the beginning...

Maurício L. (Guest)
on 2009-02-20 22:01
(Received via mailing list)
states = [ 'CA', 'TX', 'LA' ]
find(:all, :origin => @somewhere, :within => 5, :conditions=>['state
IN ( ? )',states])

Maurício Linhares (pt-br) |

On Fri, Feb 20, 2009 at 4:58 PM, Naija G.
Naija G. (Guest)
on 2009-02-22 02:12
Thanks a lot!  What if my attribute has multiple values?  For example,
if a user is associated with multiple states and the model User has an
attribute states that's a collection of strings how would I check that
against the query you showed me?  So user.states returns NY and MA, and
I'm trying to see if the given user's states is in the applicable states
for the rule?

I need to change the query to something like

user.states in states

...but it seems like I'll have to modify yours quite a bit more!

Maurício Linhares wrote:
> states = [ 'CA', 'TX', 'LA' ]
> find(:all, :origin => @somewhere, :within => 5, :conditions=>['state
> IN ( ? )',states])
> -
> Maur�cio Linhares
> (pt-br) |
> (en)
> On Fri, Feb 20, 2009 at 4:58 PM, Naija G.
This topic is locked and can not be replied to.