2016-09-22 13 views
7

私はdevisesでRails 5 APIを使用しています。私はUserモデルを持っています。スキーマはこのように見えます。Rails 5モデルオブジェクトがすべてDevits属性を表示しない

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 

しかし、私が午前問題は、唯一のモデルの一部として: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: "[email protected]", created_at: "2016-09-22 03:58:04", updated_at: "2016-09-22 04:54:41"> 

しかし、これらの属性はデータベースに存在します。この問題は先に説明しました。 Devise with rails 5。しかし答えはありません。助けてください。

+0

'User.first.to_json' –

答えて

8

工夫がencrypted_passwordなどの属性を制限し、重要な情報が取得されないようにAPI呼び出しで公開されます。したがって、これをオーバーライドするには、serializable_hashメソッドをオーバーライドする必要があります。

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

これはRails 5固有の機能ではなく、属性を保護するためのDevise機能です。

希望に役立ちます!

+0

はい。それは私が探していたものです。これは、以前のRails 4.2プロジェクトで開発されたものではありませんでした。理由は分かりませんか? – narym

+1

私は確信していませんが、DeviseはこれをRails 3でやっていましたが、これは面白いです。私はそれを徹底的に調べます。 – RSB

+1

私は以前のいくつかのRails 4プロジェクトをチェックインしましたが、すべての属性がそこに表示されています。開発3.5.5。 – narym

1

deviseが自分の内部属性を公開していないので、これはおそらくですattributes方法

User.first.attributes 
+0

これはすべての属性を与えます。しかし、なぜUser.firstにいくつかの属性しか出現していません。たとえば、@ user.to_jsonはすべての属性を追加しません。このように奇妙な宝石のjson応答を考案する。 – narym

+0

試着 '@ user.attributes.to_json' –

+0

こんにちはバートク、私はこのように属性を得ることができます。しかし、私の質問は、なぜ 'User.first'がすべての属性を表示しないのかです。 ? – narym

5

を試してみてください。

だから、すべてはあなたがto_jsonを呼び出すことができた上でハッシュを、返す(hereを文書化).attributesを使用することができます属性を取得するには:

user = User.find(1) 
user.attributes.to_json # => contains all fields like reset_password_token etc. 
関連する問題