Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - how to select all records by ID range

I am trying to do a query for all cities (selecting only their name attribute) by their ID, and I want to be able to specify a range of ID's to select. My code is below:

def list_cities(start, stop)
  cities = City.all(order: 'name ASC', id: start..stop, select: 'name')
  cities.map { |city| "<li> #{city.name} </li>" }.join.html_safe
end

However, I get an error:

Unknown key: id

My implementation in my view is:

<%= list_cities(1,22) %>

This is a helper method to be put in all views, so I am not putting the logic in a particular controller.

My schema for this model is:

  create_table "cities", :force => true do |t|
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
    t.string   "neighborhoods"
    t.string   "name"
    t.integer  "neighborhood_id"
  end

When I ran the method in my console, I got:

City Load (0.9ms)  SELECT name FROM "cities" WHERE ("cities"."id" BETWEEN 1 AND 3) ORDER  BY name ASC
 => "" 

I know it's not an issue of having an empty database since it worked with the following version of the method:

def list_cities(start, stop)
  cities = City.all(order: 'name ASC', limit: stop - start, select: 'name')
  cities.map { |city| "<li> #{city.name} </li>" }.join.html_safe
end

However, this method returns only the first 'n' records and not a range like I want.


When trying a simpler query in the console:

1.9.3p385 :009 > City.where(:id => 1..4)
  City Load (0.9ms)  SELECT "cities".* FROM "cities" WHERE ("cities"."id" BETWEEN 1 AND 4)
 => [] 

I figured out why it was happening...

I did City.all in my console and realized that my cities started with id "946" because I had seeded multiple times and the ID's were not what I thought they were! The solution offered was correct!

like image 494
Zephyr4434 Avatar asked Apr 30 '13 03:04

Zephyr4434


1 Answers

City.where(:id => start..stop).order('name ASC').select(:name)
like image 55
Danil Speransky Avatar answered Sep 26 '22 03:09

Danil Speransky