我有一个模型用户,我大量使用动态属性。 当我显示用户显示时,我跳过第一组属性以跳过标识等。 问题是属性按字母顺序排序,而不是按创建顺序排列 因此,例如,如果我创建用户为: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_"}