2016-06-11 98 views
0

我想在我的應用程序中使用rails枚舉字段的用戶狀態功能,但枚舉似乎沒有工作(我用Devise來管理用戶登錄,註冊.etc)。 這是結果在我的rails控制檯,其狀態顯示爲status:0代替status:pendingstatus:activestatus:suspended .etcRails 4.2枚舉不工作

user = User.first User Load (1.6ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 
=> #<User id: 1, email: "[email protected]", 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>' 

我怎麼修復與軌道枚舉這個問題? 謝謝!

+0

感謝您的回覆。它返回0 –

+2

您是否在''用戶'模型中添加了'enum'聲明後重新啓動了Rails控制檯嗎? – spickermann

+0

是的,它修復了它...謝謝你太多了!!!!! –

回答

0

當您更改應用程序中的代碼時,您需要重新加載或重新啓動Rails控制檯。

根據變化的類型,更快的重裝可能會解決你的問題:

> reload! 

在更大的變化:當您添加或刪除的app文件夾以外的寶石或更改代碼(例如初始化或某事在lib文件夾中),您需要完全退出並重新啓動控制檯:

> exit 
$ rails console