仅查询整数Rails 2.3

时间:2012-10-18 17:32:45

标签: regex postgresql ruby-on-rails-2

我的环境是Ruby 1.8.7-p358 with Rails 2.3.11。我正在尝试查询只有accounts只包含数字的所有first_name(它们都是3位整数,即001,143,815等)。我一直在尝试使用此查询:

Account.find(:all, :conditions => ["first_name LIKE ?", "[^0-9][^0-9][^0-9]"])

我获得的回报是=> []

如果我仅对NOT LIKE使用相同的查询,我会获得所有accounts,包括first_name为整数的那些。

我也尝试过使用:

Account.find(:all, :conditions => ["first_name REGEXP ?", "[^0-9][^0-9][^0-9]"])

但这只能给我:

ActiveRecord::StatementInvalid: PGError: ERROR:  syntax error at or near "REGEXP"
LINE 1: SELECT * FROM "accounts" WHERE (first_name REGEXP '[0-9][0-9...
                                               ^

: SELECT * FROM "accounts" WHERE (first_name REGEXP '[0-9][0-9][0-9]')  ORDER BY first_name ASC
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/connection_adapters/abstract_adapter.rb:227:in `log'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/connection_adapters/postgresql_adapter.rb:520:in `execute'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/connection_adapters/postgresql_adapter.rb:1002:in `select_raw'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/connection_adapters/postgresql_adapter.rb:989:in `select'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
      from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/base.rb:665:in `find_by_sql'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/base.rb:1582:in `find_every'
  from /Users/kyle/.rvm/gems/ruby-1.8.7-p358@popcorn_recruiter_portal/gems/activerecord-2.3.11/lib/active_record/base.rb:619:in `find'
  from (irb):189
  from :0

不允许使用正则表达式吗?我怎样才能找到account的每个first_name等于三位整数?

1 个答案:

答案 0 :(得分:2)

like运算符不评估正则表达式。相反,您可以同时使用similar to

select '980' similar to '[0-9][0-9][0-9]';
 ?column? 
----------
 t

~

select '980' ~ '[0-9][0-9][0-9]';
 ?column? 
----------
 t
(1 row)