Reputation: 42182
I have to query for a user who needs to manage a dossier. The user has a min and a max field and if the last number of the dossier number is between those 2 values the user needs to be found. This is the other way round most queries between a range work.
For the moment I have to use plain sql, the following works but I would like to use an activerecord query (the first error) or at least a safer method (second error).
For better readability I shortened the names of the fields.
dosnr = 123456
# error invalid identifier
# User.where(dosnr.to_s[-1] => :min..:max )
# error invalid character 6
# User.where("#{dosnr.to_s[-1]} between ? and ?, min, max ")
# sql works
User.where("#{dosnr.to_s[-1]} between min and max ")
How to do this without using the sql or without having to loop all the records or having to use multiple where statements ?
Upvotes: 0
Views: 284
Reputation: 13477
It's impossible to do it without SQL, because ActiveRecord doesn't support built-in methods for '<', '>' or 'BETWEEN' operators at the current moment. But you can rid of string interpolation, which is unsafe:
User.where('? between min and max', dosnr.to_s[-1])
Upvotes: 3