views:

27

answers:

2

Hello,

I have this find condition pulling from my model that currently looks like this.

 @major_set = Interest.find(:all, :conditions => {:id => 1..21})

I'd like to add some more individual ids that I've just added which are like 120...130. I tried to do...

 @major_set = Interest.find(:all, :conditions => {:id => 1..21, 120..130})

but got the error. " syntax error, unexpected '}', expecting tASSOC ...ns => {:id => 1..21, 122..130})"

How can I select multiple sets of id's as well as maybe some individual ids, ie ( :conditions => {:id => 1..21, 121..140, 144, 155 }??

+1  A: 

If you type {:id => 1..21, 122..130} inside irb you will get an error because it is not valid ruby syntax. This is interpreted as a hash where the first element is :id => 1..21 and the second is missing its key. In order to make it a valid ruby expression, you would need to type:

{:id=>[1..21, 122..130]}

But I don't think that ActiveRecord will accept that syntax. So you may need to:

:conditions => "id BETWEEN 1 AND 21 OR id BETWEEN 122 AND 130"

This works in MySQL. I don't know if it will work in other databases.

gdelfino
Will the OR make the find condition search for both sets of data? I mean including both 1...21 and 122 ...130, I mean i would need both not one OR the other; so i just wondering
ChrisWesAllen
Yes, it will. I tested it.
gdelfino
+1  A: 

You can convert the ranges to arrays and add them together. E.g.

@major_set = Interest.find(:all, 
    :conditions => {:id => (1..21).to_a + (120..130).to_a})

If you then want to add in individual ids then you can just add them to the array. E.g.

ids_to_find = (1..21).to_a + (120..140).to_a
ids_to_find << 144
ids_to_find << 145
@major_set = Interest.find(:all, :conditions => { :id => ids_to_find })
Shadwell