我有一個模型用戶,我大量使用動態屬性。 當我顯示用戶顯示時,我跳過第一組屬性以跳過標識等。 問題是屬性按字母順序排序,而不是按創建順序排列 因此,例如,如果我創建用戶爲:Mongodb mongoid模型屬性按字母順序排序不是插入順序
MONGODB startuplab_co_development['users'].insert([{"provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "_id"=>BSON::ObjectId('4dc5ad606acb26049e000002'), "email"=>"[email protected]", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio"}])
即使插入第二個屬性是uid,當我檢索鍵時,它們按字母順序排序。
%h1 User
%ul
-keys = @user.attributes.keys[3..-1]
- keys.each do |key|
%li
%span
%strong= "#{key.capitalize()}:"
%span= "#{@user[key]}"
因此,例如,這將打印UID作爲最後一個屬性,因爲它們被排序。
First_name: Daniel
Last_name: Palacio
Name: Daniel Palacio
Provider: google
Uid: https://www.google.com/accounts/o8/id?id=AItOawl_oas_8jcY1VSTQchsc
是否有無論如何我可以確保屬性位置保持插入順序?
下面是一連串事件,其中屬性得到分類
- 創建UID之後是第三屬性
ruby-1.9.2-p0 > user = User.first
=> _id: 4dc5c5946acb26049e000005, _type: nil, _id: BSON::ObjectId('4dc5c5946acb26049e000005'), provider: "google", uid: "https://www.google.com/accounts/o8/id?id=AItOawl_oas_", admin: nil, email: "[email protected]", first_name: "Daniel", last_name: "Palacio", name: "Daniel Palacio">
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "email"=>"[email protected]", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio"}
- 現在我們更新了管理屬性,並保存它, uid仍然是第3個屬性
ruby-1.9.2-p0 > user.update_attributes(:admin => true)
=> true
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "email"=>"[email protected]", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio", "admin"=>true}
ruby-1.9.2-p0 > user.save
=> true
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_", "email"=>"[email protected]", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio", "admin"=>true}
- 知道我們再次從數據庫中檢索對象,uid現在是最後一個屬性,並且它們已按字母順序排序。
ruby-1.9.2-p0 > user = User.first
=> #
ruby-1.9.2-p0 > user.attributes
=> {"_id"=>BSON::ObjectId('4dc5c5946acb26049e000005'), "admin"=>true, "email"=>"[email protected]", "first_name"=>"Daniel", "last_name"=>"Palacio", "name"=>"Daniel Palacio", "provider"=>"google", "uid"=>"https://www.google.com/accounts/o8/id?id=AItOawl_oas_"}