如何使用整数值而不是字符串查找记录

时间:2015-02-20 09:30:59

标签: ruby-on-rails activerecord casting type-conversion

我的列字段为字符串,例如ex。 start_age(“20”)和end_age(“40”)。

现在我想要年龄( 24为整数)介于start_age和age_age之间的用户。那么我怎样才能得到这个用户?

我尝试过这个查询

User.where("start_age < (?) AND end_age > (?)", age, age)

但收到此错误:

PG::UndefinedFunction: ERROR:  operator does not exist: character varying < integer

提前致谢。

1 个答案:

答案 0 :(得分:2)

写下:

User.where("start_age::integer <= :age AND end_age::integer >= :age", age: age)
# or equivalent
User.where(":age BETWEEN start_age::integer AND end_age::integer", age: age)

以下是一些演示

test_dev=# select 20  between '1'::integer and '10'::integer as result;
 result
--------
 f
(1 row)

test_dev=# select 5  between '1'::integer and '10'::integer as result;
 result
--------
 t
(1 row)

test_dev=# select '12'::integer as number;
 number
--------
     12
(1 row)