Rails 4.2 枚举不工作

Rails 4.2 enum not working

我正在尝试在我的应用程序中使用 rails 枚举字段作为用户状态功能,但枚举似乎不起作用(我使用 Devise 来管理用户登录、注册等)。 这是我的 rails 控制台中的结果,其中状态显示为 status:0 而不是 status:pending status:active status:suspended.etc

  user = User.first   User Load (1.6ms)  SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 1
 => #<User id: 1, email: "email@gmail.com", encrypted_password:
 "a$TFSX2XkearxEz1JlRtd6hOcvj3ScqykNKEKrkqGYLDx...",
 reset_password_token: nil, reset_password_sent_at: nil,
 remember_created_at: nil, sign_in_count: 1, current_sign_in_at:
 "2016-06-10 22:57:03", last_sign_in_at: "2016-06-10 22:57:03",
 current_sign_in_ip: "::1", last_sign_in_ip: "::1", created_at:
 "2016-06-10 22:57:03", updated_at: "2016-06-11 10:59:41", first_name:
 "John", last_name: "Smith", phone: nil, **status: 0**>

但我已经在 user.rb

中声明了状态枚举
  class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  enum status: [:pending, :active, :suspended]
end

这是我的迁移

class AddStatusColumn < ActiveRecord::Migration
  def change    
    add_column :users, :status, :integer, default: 0    
  end
end

此外,当我使用 user.pending?(默认)时,我得到一个错误 "undefined method `pending?'" 例如

    irb(main):014:0> user.pending?
NoMethodError: undefined method `pending?' for #<User:0x315dba8>
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activemodel-4.2.6/lib/active_model/attribute_methods.rb:433:in `method_missing'
        from (irb):14
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

如何解决 rails 枚举的这个问题? 谢谢!

当您更改应用程序中的代码时,您需要重新加载或重新启动 Rails 控制台。

根据更改的类型,更快的重新加载可能会解决您的问题:

> reload!

关于更大的更改:当您在 app 文件夹之外添加或删除 gem 或更改代码(例如 lib 文件夹中的初始化程序或其他内容)时,您将需要退出并重新启动控制台完全:

> exit
$ rails console