Rails return JSON serialized attribute with_indifferent_access

前端 未结 4 1438
日久生厌
日久生厌 2021-02-07 05:55

I previously had:

serialize :params, JSON

But this would return the JSON and convert hash key symbols to strings. I want to reference the hash

4条回答
  •  灰色年华
    2021-02-07 06:38

    Posting comment as answer, per @fguillen's request... Caveat: I am not typically a Rubyist… so this may not be idiomatic or efficient. Functionally, it got me what I wanted. Seems to work in Rails 3.2 and 4.0...

    In application_helper.rb:

    module ApplicationHelper
      class JSONWithIndifferentAccess
        def self.load(str)
          obj = HashWithIndifferentAccess.new(JSON.load(str))
          #...or simply: obj = JSON.load(str, nil, symbolize_names:true)
          obj.freeze #i also want it set all or nothing, not piecemeal; ymmv
          obj
        end
        def self.dump(obj)
          JSON.dump(obj)
        end
      end
    end
    

    In my model, I have a field called rule_spec, serialized into a text field:

    serialize :rule_spec, ApplicationHelper::JSONWithIndifferentAccess
    

    Ultimately, I realized I just wanted symbols, not indifferent access, but by tweaking the load method you can get either behavior.

提交回复
热议问题