Rails - 传递给控制器​​的JSON评估为nil

时间:2016-06-13 21:10:18

标签: ruby-on-rails json

我正在尝试将JSON传递给控制器​​作为我的Rails应用程序中的参数,但它始终抛出错误,表示该参数为nil。

JSON由视图中的用户输入汇编,并通过单击e=10001h元素传递给控制器​​,如下所示:

#summary

点击var url = $('#summary').attr('href') + '?report={datetime:"2016-06-13 08:38:04",weather_id:"1",location_description:"home",latitude:"12",longitude:"34",accuracy:"56",wildlife:"cat",comments:"test",report_type_id:"1",wetland_feature_id:"1",wetland_number:"101"}'; $('#summary').attr('href', url); 后,我的控制台显示视图:

#summary

最后,在控制器中,我尝试用

取出JSON
Started GET "/users/sign_in?report={datetime:%222016-06-13%2008:38:04%22,weather_id:%221%22,location_description:%22home%22,latitude:%2212%22,longitude:%2234%22,accuracy:%2256%22,wildlife:%22cat%22,comments:%22test%22,report_type_id:%221%22,wetland_feature_id:%221%22,wetland_number:%22101%22}" for ::1 at 2016-06-13 16:58:26 -0400
Processing by Users::SessionsController#new as HTML
Parameters: {"report"=>"{datetime:\"2016-06-13 08:38:04\",weather_id:\"1\",location_description:\"home\",latitude:\"12\",longitude:\"34\",accuracy:\"56\",wildlife:\"cat\",comments:\"test\",report_type_id:\"1\",wetland_feature_id:\"1\",wetland_number:\"101\"}"}

但@incomingReport在我尝试@incomingReport = (params[:report]) 时始终评估为nil,例如NoMethodError (undefined method 'each' for nil:NilClass)。我也做了一些其他的测试,比如

@incomingReport.each

,确实已将if (params[:report]).nil? puts "Yep, nil" end 打印到我的控制台。

我确信我首先在格式化参数的方式有问题,但我不确定是什么。任何帮助将不胜感激。

编辑以显示更多控制器代码

Yep, nil

1 个答案:

答案 0 :(得分:0)

如果要访问查询参数,请使用URI和CGI库

url    = 'http://www.foo.com?id=4&empid=6'
uri    = URI.parse(url)
params = CGI.parse(uri.query)
# params is now {"id"=>["4"], "empid"=>["6"]}

id     = params['id'].first
# id is now "4"

那就是说我觉得这对你遇到的问题是一个肮脏的解决方案,但这就是你要求的。

允许现有控制器访问此参数,您可以更改此信息:

def report_params(params)
  params.permit(:user_id, :report_type_id, :datetime, :weather_id, :location_description, :latitude, :longitude, :accuracy, :comments, :wildlife, :other_weather, :wetland_feature_id, :other_wetland_feature, :wetland_number)
end

def report_params(params)
  params.permit(:user_id, :report_type_id, :datetime, :weather_id, :location_description, :latitude, :longitude, :accuracy, :comments, :wildlife, :other_weather, :wetland_feature_id, :other_wetland_feature, :wetland_number, :report)
end