Rails -JSON传递到控制器将评估为零



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

JSON在视图中由用户输入组装,并通过单击#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之后,我的控制台的视图:

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"}"}

最后,在控制器中,我尝试将JSON带回去

@incomingReport = (params[:report])

但是@incomingReport始终评估nil,例如NoMethodError (undefined method 'each' for nil:NilClass)尝试执行@incomingReport.each时。我也做了其他测试,例如

if (params[:report]).nil?
    puts "Yep, nil"
end

,哪个,肯定将Yep, nil打印到我的控制台。

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

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

def create
    self.resource = warden.authenticate!(auth_options)
    incomingReport = params[:report]
    puts incomingReport
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
end
private
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

如果要访问查询参数,请使用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

to

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

最新更新