Rails 4.2枚举不起作用

时间:2016-06-11 13:49:50

标签: ruby-on-rails ruby enums devise ruby-on-rails-4.2

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

  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:
 "$2a$11$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?(默认)时,我得到一个错误“未定义的方法`待定?'”例如

    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枚举修复此问题? 谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

> reload!

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

> exit
$ rails console