ActiveRecord 对象 ruby​​ 3.0 上的 to_json

pk-*_*k-n 5 ruby-on-rails ruby-3

我正在使用 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>替换为它的所有属性。

知道我缺少什么吗?

Seb*_*lma 4

问题出在 Rails 6.0.3.6 中,当调用to_jsonRails{'user' : User.first }最终添加一个JSON::Ext::Generator::State参数时to_json,因此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
Run Code Online (Sandbox Code Playgroud)

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

所以,就你而言,你可以这样做

{ 'user': User.first.attributes }.to_json
Run Code Online (Sandbox Code Playgroud)

绕过这个问题。