rails 2.3.4中json库的向后兼容性问题

时间:2009-12-03 10:31:22

标签: ruby-on-rails

rails 2.0.2中用于对象的

to_json方法(比如带有id和name的用户模型对象)用于提供表单中的简单输出

{"id":"xyz","name":"hello"}

但是在将轨道升级到2.3.4时,它会将输出显示为

{"user":{"id":"xyz","name":"hello"}}

这打破了我的大部分前端代码。

有没有办法以与2.0.2相同的方式获得结果???

寻找你们的快速回答!!

1 个答案:

答案 0 :(得分:0)

您需要编辑文件config/initializers/new_rails_defaults.rb并将ActiveRecord::Base.include_root_in_json = true更改为false。应该这样做。请参阅to_json文档。

如果由于某种原因你没有该文件,这就是它在默认的Rails 2.3.x应用程序中的样子。

# Be sure to restart your server when you modify this file.

# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.

if defined?(ActiveRecord)
  # Include Active Record class name as root for JSON serialized output.
  ActiveRecord::Base.include_root_in_json = true

  # Store the full class name (including module namespace) in STI type column.
  ActiveRecord::Base.store_full_sti_class = true
end

# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true

# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false