Rails 1.2.2 and ranges in AR conditions clause.

Hi,

According to Jamis' blog post:

You can do this in RoR 1.2.2: Student.find(:all, :conditions => { :grade => 9..12 })

which automatically get converted into: SELECT * FROM students WHERE grade BETWEEN 9 AND 12

but when I try this:

Customer.find :all, :conditions => [:id => 1..2] # loaded from fixture customer.yml

I get:

NoMethodError: undefined method `%' for {:id=>1..2}:Hash         from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_record/base.rb:1419:in `sanitize_sql_array'         from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_record/base.rb:1388:in `sanitize_sql'         from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_record/base.rb:1164:in `add_conditions!'         from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_record/base.rb:1097:in `construct_finder_sql'         from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_record/base.rb:997:in `find_every'         from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_record/base.rb:418:in `find'         from (irb):2

Can anyone help?

Thanks Ed

Hi Ed,

Ed Howland wrote:

Student.find(:all, :conditions => { :grade => 9..12 })

but when I try this:

Customer.find :all, :conditions => [:id => 1..2]

I get:

NoMethodError: undefined method `%' for {:id=>1..2}:Hash

I think your problem is in the use of instead of {} as in Jamis' blog.

hth, Bill

Duh! Thanks, Bill.

That was it. I guess I was just so used to using for the conditions value.

Ed

you could also do

Customer.find((1..2).to_a)

which is shorter in code, but could possibly cause problems if you have a large range

Customer.find((1..2).to_a) SELECT * FROM stories WHERE (stories."id" IN (1,2,3,4,5))

Customer.find(:all, :conditions => { :id => (1..2) }) SELECT * FROM stories WHERE (stories."id" BETWEEN 1 AND 5)

Chris,

Thanks, but I am actually trying to use this for Date ranges.

(Time.local(2007, 3, 1)..Time.local(2007, 4, 1)).to_a takes a REALLY LONG TIME to complete. Probably because it is generating every second?

I have another question. Given : :conditions => {:created_on => Time.local(2007, 3, 1)..Time.local(2007, 4, 1)}

how can I combine this with other conditions in the query? Normally, I can manipulate the elements of the array (append " and " + new clause to conditions[0] and append new value to conditions). But given that I must supply a hash here to #find, I don't see how to combine any other conditions.

Ed