[英]How to access nested json params in a post request with Ruby on Rails on the backend
I need to access the json parameters from a form post request in a Ruby on Rails backend controller.我需要从 Rails 后端 controller 上的 Ruby 中的表单发布请求访问 json 参数。 I need to access a model object (carrier-type), in order to get the id.
我需要访问 model object(运营商类型)才能获得 id。 However, I keep getting the following error.
但是,我不断收到以下错误。 Can anyone advise how I would access this data?
谁能建议我如何访问这些数据?
Error:错误:
undefined method `[]' for nil:NilClass excluded from capture: DSN not set
app_1 |
app_1 | NoMethodError (undefined method `[]' for nil:NilClass):
Sample Json Data:样品 Json 数据:
{"_jsonapi"=>
{"data"=>
{"attributes"=> {"device"=>mobile},
"relationships"=>
{"carrier-type"=>{"data"=>{"id"="1}}}
}
}
}
}
Access Attempt:访问尝试:
I have tried the following我试过以下
@myParams = params[:_jsonapi];
Rails.logger.info("STARTTIME PARAMS: #{@myParams}")
You must be trying to access the id
in the following way您必须尝试通过以下方式访问
id
params["_jsonapi"]["data"]["relationships"]["carrier-type"]["data"]["id"]
this can throw you an error if any of the previous key will not be there in your JSON.如果您的 JSON 中没有任何先前的密钥,这可能会给您带来错误。
ie IE
params["_jsonapi"]["key_that_is_not_present"]["relationships"]["carrier-type"]["data"]["id"]
will through error like:将通过以下错误:
NoMethodError (undefined method `[]' for nil:NilClass)
I would suggest you to use dig
here.我建议你在这里使用
dig
。
params.dig("_jsonapi", "data", "relationships", "carrier-type", "data", "id")
in this way you will not get an error but if any key is not present you will get nil
ie这样你就不会得到一个错误,但如果任何键不存在你将得到
nil
即
params.dig("_jsonapi", "random_key")
will return nil
将返回
nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.