我在Rails应用程序中看到了一些奇怪的行为。我正在运行ruby 1.9.2-p290,我有这种控制器:
class NumbersController < ApplicationController
def index
render :json => [1,2,3]
end
end
想象一下,我运行这样的服务器来演示问题:
$ rails s # This one runs in "development" on port 3000
$ RAILS_ENV=production rails s -p 2999 # This one runs in "production" on port 2999
在开发或测试模式下,我的结果将是
$ curl localhost:3000/numbers # development
{numbers: [1,2,3]} # The root is being included in the json, as inferred from the controller name.
$ curl localhost:2999/numbers # production
[1,2,3] # No root in the JSON
我已经使用细齿梳在应用程序上,并且没有明显的配置差异,看起来它们会影响开发和生产之间的json。此外,没有像“if Rails.env ==='production'”
这样的行我猜测需要不同的宝石,例如对于正在改变渲染行为的资产:json =&gt; ......我已经在运行的应用程序中检查了“json”和“multi_json”gems的版本,它们是相同的(分别为1.7.5和1.3.6,multi_json使用相同的适配器)。如何在应用程序运行时从 中确切了解哪些宝石需要?此外,有没有人有任何替代解释?
编辑:我正在运行Rails 3.1.1,我的Gemfile的资产部分是:
group :assets do
gem "ember-rails"
gem "jquery-rails"
gem "less", "2.0.7"
gem "less-rails", "2.0.2"
gem 'uglifier'
end
答案 0 :(得分:3)
我在这里找到了一个解决方法:include_root_in_json from controller
解决方案:
render :json => {:numbers => [1,2,3]}, :root => false # If you want the root
:root =&gt;在生产中没有得到尊重。我怀疑在那种环境中,as_json或to_json被错误地覆盖了。
我仍然不高兴,因为我不能依赖渲染:json =&gt; [1,2,3]。
答案 1 :(得分:1)
我正在寻找以下配置:
ActiveRecord::Base.include_root_in_json
它恰好产生了对象的JSON表示之间的差异:如果设置为true,则将对象名称添加为生成的JSON的根键。
答案 2 :(得分:1)
此行为由config / initializers / wrap_parameters.rb中的此设置控制,适用于新的rails应用。
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
可能是因为您的控制器没有引用任何AR(ActiveRecord)类,由于开发模式下的延迟加载,AR尚未加载。因此设置是正确的。
您可以通过将ActiveRecord::Base
放入索引操作来强制加载来测试该理论。
答案 3 :(得分:0)
如何在应用中准确找出所需的宝石 它正在运行?
Gemfile.lock
文件指定了这个。