Getting hash with symbol as keys for mongo in rails

前端 未结 2 1823
南笙
南笙 2021-01-18 20:07

The Mongo ruby driver seems to get put your results into a hash with strings as keys. Is there a way to tell it to convert the keys into symbols instead?

相关标签:
2条回答
  • 2021-01-18 20:26

    According to the FAQ, Even though there is a symbol type in Mongo, and you can store symbols in values, the BSON format specifies that keys must be strings.

    0 讨论(0)
  • 2021-01-18 20:38

    If you have a Hash that is keyed with strings, and you want to be able to use Symbols as keys to access its values, you can use a HashWithIndifferentAccess. If you are not using Rails, you can get this class via the ActiveSupport gem.

    my_hash = { 'name' => 'Joe', 'email' => 'joe@schmoe.com' }
    my_hash = HashWithIndifferentAccess.new my_hash
    puts my_hash[:name] # "Joe"
    
    0 讨论(0)
提交回复
热议问题