开发者

Rails -- Find condition with id's all over the place

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 individua开发者_StackOverflowl ids, ie ( :conditions => {:id => 1..21, 121..140, 144, 155 }??


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 })


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜