Find Multiple Conditions

Hi,

I’m getting my records using:

@users= User.find(:all,:conditions=>["country=? ",country])

where country is a String with the name of the country.

But now I want to get the result for different countries.
I have an array
countries = [‘Germany’,‘France’,‘Spain’]

and I want to get all the records where country is one of those
included in the array

How can I do that?

Thanks

cfingerh wrote:

But now I want to get the result for different countries.
I have an array
countries = [‘Germany’,‘France’,‘Spain’]

and I want to get all the records where country is one of those
included in the array

The following suggestion is a detestable hack, but it works. The names
of
countries (someone correct my logic here) don’t contain single or double
quotes, right? That means my hack will work, regardless how a database
escapes quotes within strings:

:conditions=> "country in (#{ countries.map(&:inspect).join(’,’) }) "

The &:inspect is a trick to put quotes around each country’s name.

And no post advising SQL abuse would be complete without warning against
SQL-insertion attacks. .inspect makes those impossible too, but at the
cost
of very probably crashing your query.

Remember that ActiveRecord does Ruby things better than SQL things at
times,
meaning to get the most out of your queries you ought to learn more SQL
SELECT statements. And there might also be a better Rails way to do what
I
did.


Phlip
http://www.oreilly.com/catalog/9780596510657/
“Test Driven Ajax (on Rails)”
assert_xpath, assert_javascript, & assert_ajax

ActiveRecord deals with this perfectly nicely,
as part of its “sanitize_sql_array” method.

countries = [“Germany”, “France”, “Spain”]

User.find(:all, :conditions => [“country IN (?)”, countries])

the countries will be escaped correctly and seperated with commas.
This will fail if countries turns out to be empty,

so you’ll need to handle that case seperately.

fingerh wrote:

Hi,

I’m getting my records using:

@users= User.find(:all,:conditions=>["country=? ",country])

where country is a String with the name of the country.

But now I want to get the result for different countries.
I have an array
countries = [‘Germany’,‘France’,‘Spain’]

and I want to get all the records where country is one of those
included in the array

How can I do that?

Thanks

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs