Rails 5模型对象未显示所有Devise属性
我正在使用Rails 5 API和设计。 我有一个User
模型。 Schema看起来像这样。
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.inet "current_sign_in_ip" t.inet "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["email"], name: "index_users_on_email", unique: true, using: :btree t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree end
但我遇到的问题是Rails只显示:id , :email , :created_at , :updated_at
属性作为模型的一部分。 例如,在rails控制台中
User.new => # User.first User Load (0.5ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1 [["LIMIT", 1]] => #
但是这些属性存在于数据库中。这个问题在前面提到过。 设计导轨5 。 但那里没有答案。请帮忙。
Devise限制了像encrypted_password
这样的属性,因此关键信息不会在API调用中暴露出来。 因此,要覆盖它,您需要覆盖serializable_hash
方法。
def serializable_hash(options = nil) super(options).merge(encrypted_password: encrypted_password) end
这不是Rails 5特有的function,而是用于保护属性的Devisefunction。
希望有所帮助!
这可能是因为devise
没有暴露其内部属性。
因此,要获取所有属性,您可以使用.attributes
( 此处记录 )返回一个哈希,您可以在其上调用to_json
:
user = User.find(1) user.attributes.to_json # => contains all fields like reset_password_token etc.
尝试attributes
方法
User.first.attributes