【问题标题】:Devise with rails 5用rails 5设计
【发布时间】:2016-07-17 07:48:25
【问题描述】:

我正在使用 devise 在 rails 5 中制作应用程序。但是在迁移设计使用的用户模型后,结果如下:

User.new =>
    User id: nil,
    email: "",
    created_at: nil,
    updated_at: nil. 

while 应该显示为:

User id: nil,
email: "",
encrypted_password: "",
reset_password_token: nil,
reset_password_sent_at: nil,
remember_created_at: nil,
sign_in_count: 0,
current_sign_in_at: nil,
last_sign_in_at: nil,
current_sign_in_ip: nil,
last_sign_in_ip: nil,
created_at: nil,
updated_at: nil,
name: nil

这意味着没有创建字段。但是当我看到 mysql 数据库时,所有字段都在 users 表中创建。那为什么它没有显示在 rails 控制台内?

以下是 schema.rb:

ActiveRecord::Schema.define(version: 20160717050914) do

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "failed_attempts",        default: 0,  null: false
    t.string   "unlock_token"
    t.datetime "locked_at"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["unlock_token"], name: "index_users_on_unlock_token", unique: true
  end

end

【问题讨论】:

  • reload! 你的 rails 控制台了吗?

标签: ruby-on-rails-5


【解决方案1】:

这是因为devise 覆盖了检查方法,不显示它们的内部属性。看到这个:https://github.com/plataformatec/devise/blob/29142418bade74224d98bbf5bbcadfba181d5db9/lib/devise/models/authenticatable.rb#L119-L124

不管怎样,他们就在那里。只是没有在inspect 方法中打印出来。

要查看您可以使用的所有属性:

user = User.first
user.attributes # => returns a hash containing all the attributes 

或者例如获取current_sign_in_ip:

user.current_sign_in_ip # => #<IPAddr: IPv4:xxx.xxx.xxx.xxx/255.255.255.0>

【讨论】:

    【解决方案2】:

    Devise 通过覆盖默认的inspect 方法来限制encrypted_password 等属性,这样关键信息就不会在API 调用中暴露。所以要覆盖这个,你需要覆盖serializable_hash 方法:

    def serializable_hash(options = nil) 
      super(options).merge({ encrypted_password: encrypted_password }) 
    end
    

    查看讨论here

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2016-11-03
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多