我正在用设计在rails 5中制作一个应用程序。但是,在迁移了用户模型之后,通过设计得到了如下结果:
User.new =>
User id: nil,
email: "",
created_at: nil,
updated_at: nil. 虽然它应该显示如下:
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发布于 2016-09-22 07:44:10
这是因为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>发布于 2016-09-22 08:17:49
通过覆盖默认的encrypted_password方法来设计像inspect这样的限制属性,这样关键信息就不会在API调用中公开。因此,要覆盖这一点,您需要重写serializable_hash方法:
def serializable_hash(options = nil)
super(options).merge({ encrypted_password: encrypted_password })
end查看讨论here。
https://stackoverflow.com/questions/38419030
复制相似问题