drlelon
November 21, 2006, 3:14pm
1
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
drlelon
November 21, 2006, 3:28pm
2
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.
drlelon
November 21, 2006, 4:21pm
3
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
drlelon
November 21, 2006, 4:43pm
4
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’)