【问题标题】:to_json on ActiveRecord object ruby 3.0ActiveRecord 对象 ruby​​ 3.0 上的 to_json
【发布时间】:2021-03-30 12:47:47
【问题描述】:

我正在使用 rails 6.0.3.6 和 ruby​​ 3.0.0,

当我打电话给{'user' : User.first }.to_json 时,我收到了"{\"user\":\"#<User:0x00007fa0a8dae3c8>\"}"

[User.first, User.last].to_json相同

如果我切换回 ruby​​ 2.7.2, 我得到了正确的结果,即<User:0x00007fa0a8dae3c8> 替换为它的所有属性。

知道我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby-3


    【解决方案1】:

    问题出在 Rails 6.0.3.6 中,当在 {'user' : User.first } 上调用 to_json 时,Rails 最终会为 to_json 添加一个 JSON::Ext::Generator::State 参数,因此 options.is_a?(::JSON::State) 返回 true 并返回 super(options)

    来自to_json的定义:

    def to_json(options = nil)
      if options.is_a?(::JSON::State)
        # Called from JSON.{generate,dump}, forward it to JSON gem's to_json
        super(options)
      else
        # to_json is being invoked directly, use ActiveSupport's encoder
        ActiveSupport::JSON.encode(self, options)
      end
    end
    

    而在最近的 Rails 中,to_json 在没有任何参数的情况下被调用,并且分支采用最终返回 ActiveSupport::JSON.encode(self, options) 的路径。

    所以,你可以这样做

    { 'user': User.first.attributes }.to_json
    

    绕过问题。

    【讨论】:

      【解决方案2】:
        {'user': User.first }.as_json
      

      使用 as_json 代替 to_json

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-22
        • 2012-11-13
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-19
        • 1970-01-01
        相关资源
        最近更新 更多