如何将所有 RoR 模型的 include_root_in_json 设置为 false?
如何将所有 RoR 模型的 include_root_in_json 设置为 false?
我尝试在 application.rb 中设置 ActiveModel::Base.include_root_in_json = false ,但没有效果。
How can i set include_root_in_json to false for all my RoR models?
I've tried to set ActiveModel::Base.include_root_in_json = false inside application.rb, but it has no effect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
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 文件中。
Model.to_json method is used to returns a JSON string representing the model and i have used
self.include_root_in_json = false in a model itself.
But for the whole application you can try setting ActiveModel::Base.include_root_in_json = false in an initializer.[edit This does not work.]
[edit] ActiveRecord::Base.include_root_in_json = true try adding this line to config/environment.rb file.
我不确定这对于 Rails 的更高版本是否成立,但对于我(运行 2.3.5 atm)来说, /config/initializers/new_rails_defaults.rb 中已经有此设置的声明,其中它被设置为:
所以如果如果您尝试在其他地方设置此设置,那么它可能会被覆盖。
I'm not sure if this is true for the later versions of rails but for me (running 2.3.5 atm) there was already a declaration for this setting in /config/initializers/new_rails_defaults.rb where it was set to:
So if you try to set this setting in another place then it might be overridden.
在 Rails 3.2.2 上,这已在初始化程序中设置:
---
config/initializers/wrap_parameters.rb
---On Rails 3.2.2, this is already set in the initializers:
---
config/initializers/wrap_parameters.rb
---对于默认的系统范围配置,在初始化程序中设置变量始终是个好主意,例如 config/initializers/defaults.rb
For default system wide config is alway good idea to set variable in initializers, like config/initializers/defaults.rb
我认为你应该在 config/application.rb 中设置 ActiveRecord::Base.include_root_in_json = false
而不是 ActiveModel::Base
I think you should set ActiveRecord::Base.include_root_in_json = false in config/application.rb
not ActiveModel::Base
在 Rails 4 的“config/initializers/wrap_elements.rb”中,您可以取消注释以下内容:
At Rails 4 in "config/initializers/wrap_elements.rb" you can uncomment the following: