Extract find conditions from array

Hi,

I have an array that contains list IDs. I want to be able to use all of
those list IDs to create an OR query.

My code is:

Contact_List.find(:all,
:select => ‘DISTINCT contact_id’,
:conditions => [‘list_id = ?’, params[:joblist][:list_id]])

but this yields the following query which is obviously incorrect:

SELECT DISTINCT contact_id FROM contact_lists WHERE (list_id = ‘2’,‘3’)

How can I get a query that reads:

SELECT DISTINCT contact_id FROM contact_lists WHERE (list_id = ‘2’ OR
list_id = ‘3’)

Thanks,

David

David L. wrote:

Hi,

I have an array that contains list IDs. I want to be able to use all of
those list IDs to create an OR query.

My code is:

Contact_List.find(:all,
:select => ‘DISTINCT contact_id’,
:conditions => [‘list_id = ?’, params[:joblist][:list_id]])

but this yields the following query which is obviously incorrect:

SELECT DISTINCT contact_id FROM contact_lists WHERE (list_id = ‘2’,‘3’)

How can I get a query that reads:

SELECT DISTINCT contact_id FROM contact_lists WHERE (list_id = ‘2’ OR
list_id = ‘3’)

Thanks,

David

Using an “in” clause should accomplish the same thing:

Contact_List.find(:all,
:select => ‘DISTINCT contact_id’,
:conditions => [‘list_id in ?’, “(’” +
params[:joblist][:list_id].join("’,’") + “’)”])

No chance to test for you, but I think the above should result in:

SELECT DISTINCT contact_id FROM contact_lists WHERE (list_id in
(‘1’,‘2’,‘3’,‘4’))

And give you the results you’re after.

c.

Cayce B. wrote:

Using an “in” clause should accomplish the same thing:
Contact_List.find(:all,
:select => ‘DISTINCT contact_id’,
:conditions => [‘list_id in ?’, “(’” +
params[:joblist][:list_id].join("’,’") + “’)”])

Also no testing, but I believe Rails will do the joining for you (which
is partly why his original attempt resulted in the way it did). So the
above code can be simplified to:

Contact_List.find :all, :select => ‘DISTINCT contact_id’,
:conditions => [‘list_id IN (?)’, params[:joblist][:list_id]]

Eric

On 11/21/06, David L. [email protected] wrote:

Contact_List.find(:all,
:select => ‘DISTINCT contact_id’,
:conditions => [‘list_id = ?’,
params[:joblist][:list_id]])

Try with this:

Contact_List.find_by_list_id(params[:joblist][:list_id]], :select =>
‘DISTINCT contact_id’)

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