【问题标题】:Rails 5 model objects not showing all Devise attributesRails 5模型对象未显示所有设计属性
【发布时间】:2016-09-22 07:21:34
【问题描述】:

我正在使用带有设计的 Rails 5 API。我有一个User 模型。架构如下所示。

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 id: nil, email: "", created_at: nil, updated_at: nil> 

 User.first
  User Load (0.5ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => #<User id: 2, email: "your@email.com", created_at: "2016-09-22 03:58:04", updated_at: "2016-09-22 04:54:41"> 

但是这些属性存在于数据库中。这个问题前面已经提到过。 Devise with rails 5 。但那里没有答案。请帮忙。

【问题讨论】:

  • User.first.to_json

标签: ruby-on-rails devise ruby-on-rails-5


【解决方案1】:

Devise 限制 encrypted_password 等属性,以便关键信息不会在 API 调用中暴露。所以要覆盖这个,你需要覆盖serializable_hash方法。

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

这不是 Rails 5 特有的功能,而是用于保护您的属性的设计功能。

希望有帮助!

【讨论】:

  • 是的。这就是我要找的。这在早期使用 devise 构建的 Rails 4.2 项目中没有发生。不知道为什么?
  • 我不确定,但 Devise 在 Rails 3 中曾经这样做过,但这很有趣。我会调查的。
  • 我刚刚检查了一些我早期的 Rails 4 项目,所有属性都显示在那里。设计 3.5.5。
  • 为什么不直接使用.attributes 而不是覆盖设计方法?
【解决方案2】:

这可能是因为devise 没有暴露其内部属性。

所以要获取所有属性,您可以使用.attributes(记录在案的here)返回一个哈希,您可以在其上调用to_json

user = User.find(1)
user.attributes.to_json # => contains all fields like reset_password_token etc.

【讨论】:

    【解决方案3】:

    试试attributes方法

    User.first.attributes
    

    【讨论】:

    • 这给出了所有的属性。但是为什么 User.first 只出现了一些属性。例如,@user.to_json 不会添加所有属性。从而弄乱了设计 gem 的 json 响应。
    • 试试@user.attributes.to_json
    • 嘿 Bartek,我可以通过这种方式获取属性。但我的问题是,为什么User.first 不显示所有属性。 ?
    • 我认为设计保护数据湖。
    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多