Rails 4.1枚举错误的地方

时间:2014-05-01 10:40:46

标签: ruby-on-rails postgresql activerecord enums

今天我想把我的Postgres枚举改为Rails 4.1 enum。 我做了一些步骤。

迁移:

 create_table :users do |t|
   # other column here
   t.column :status, :integer
 end
模特中的

class User < ActiveRecord::Base
  enum status: [ :local, :tourist ]
end

现在创建用户:

  => User.create(email: 'ffoo@mai.com', password: '12345678', status: 'local')
  => #<User id: "53621ec84d6163124", email: "ffoo@mai.com", status: 0, ......>
  => u = User.last
  => User Load (0.9ms)  SELECT  "users".* FROM "users" ........
  => #<User id: "53621ec84d6163124", email: "ffoo@mai.com", status: 0, ......>
  => u.local?
  => true

尝试查找本地用户(现在我的枚举有奇怪的行为):

  => User.where("status <> ?", User.statuses[:local])
  => User Load (0.9ms)  SELECT "users".* FROM "users"  WHERE (status <> 0)
  => []

WTF?

  => User.where("status <> ?", User.statuses[:tourist])
  => User Load (0.9ms)  SELECT "users".* FROM "users"  WHERE (status <> 1)
  => #<User id: "53621ec84d6163124", email: "ffoo@mai.com", status: 0, ......>

问题是,此查询User.where("status <> ?", User.statuses[:local])应该返回我的本地用户。或者我做错了什么?

1 个答案:

答案 0 :(得分:4)

您在这里使用了错误的操作员。

"status <> ?" equals  "status != ?"

相反,您想要使用

"status = ?"

Postgres comparison operators