Topic: Searching ID Ranges

This one should easy peasy
I need to return a range of ids thats all.
But I get Couldn't find Info with ID=2..5
so it's taking 2..5 as a litaral word.. Hmph

  @info_pages = Paginator.new self, Info.count, 10, params[:page]
        @infos = Info.find((2..5),
                              :limit  =>  @info_pages.items_per_page,
                              :offset =>  @info_pages.current.offset)

Re: Searching ID Ranges

Try:

Info.find((2..5).to_a)

This will do a separate find for each one, so if one is missing it will raise an error.

Probably better is to do this with conditions:

find(:all, :conditions => ['id >= ? AND id <= ?', 2, 5])

Railscasts - Free Ruby on Rails Screencasts

Re: Searching ID Ranges

edit2: ^^ couldn't you also use BETWEEN in SQL?

Use to_a

(2..5).to_a
=> [2, 3, 4, 5]

edit: beaten by ryan!

vinnie - rails forum admin

Re: Searching ID Ranges

vin wrote:

edit2: ^^ couldn't you also use BETWEEN in SQL?

Yep. Good catch. I think you need to add one to include the last number though.

find(:all, :conditions => ['id BETWEEN ? AND ?', 2, 5+1])

Edit: oh fun!

The BETWEEN...AND operator is treated differently in different databases. With some databases a person with the LastName of "Hansen" or "Pettersen" will not be listed (BETWEEN..AND only selects fields that are between and excluding the test values). With some databases a person with the last name of "Hansen" or "Pettersen" will be listed (BETWEEN..AND selects fields that are between and including the test values). With other databases a person with the last name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND selects fields between the test values, including the first test value and excluding the last test value). Therefore: Check how your database treats the BETWEEN....AND operator!

Found at: http://www.w3schools.com/sql/sql_between.asp

Railscasts - Free Ruby on Rails Screencasts

Re: Searching ID Ranges

Aw sweat find(:all, :conditions => ['id >= ? AND id <= ?', 2, 5])  does it ! big_smile many thanks