我如何将所有 RoR 模型的 include_root_in_json 设置为 false?
我尝试在 application.rb 中设置 ActiveModel::Base.include_root_in_json = false,但它没有效果。
我如何将所有 RoR 模型的 include_root_in_json 设置为 false?
我尝试在 application.rb 中设置 ActiveModel::Base.include_root_in_json = false,但它没有效果。
Model.to_json 方法用于返回代表模型的 JSON 字符串,我在模型本身中使用 了self.include_root_in_json = false。
但是对于整个应用程序,您可以尝试在初始化程序中设置ActiveModel::Base.include_root_in_json = false。[编辑这不起作用。]
[编辑] ActiveRecord::Base.include_root_in_json = true尝试将此行添加到 config/environment.rb 文件。
我不确定这是否适用于更高版本的 rails 但对我来说(运行 2.3.5 atm)已经在 /config/initializers/new_rails_defaults.rb 中声明了这个设置,它被设置为:
ActiveRecord::Base.include_root_in_json = true
因此,如果您尝试在其他地方设置此设置,那么它可能会被覆盖。
在 Rails 3.2.2 上,这已经在初始化程序中设置:
--- config/initializers/wrap_parameters.rb
---
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
对于默认系统范围的配置,在初始化程序中设置变量总是一个好主意,例如 config/initializers/defaults.rb
我认为您应该在 config/application.rb 中设置 ActiveRecord::Base.include_root_in_json = false
不是 ActiveModel::Base
在“config/initializers/wrap_elements.rb”中的 Rails 4 中,您可以取消注释以下内容:
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = true
end