强参数和 json 输入 rails 4 [英] strong parameter and json input rails 4

查看:35
本文介绍了强参数和 json 输入 rails 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过嵌套关联属性的 JSON 字符串保存数据.我不想使用 attr_accessible.我几乎得到了强参数的逻辑,但仍然遇到了使它们工作的问题.我正在获取 JSON 字符串并使用它来保存数据

I am trying to save data through JSON String in which I have nested associated attributes. I do not want to use attr_accessible. I almost got the logic of strong parameter but still got the problem to make them work. I am getting JSON string and using it to save data using this

data = request.body.read
@inputData = Person.new(JSON.parse(data))
@inputData.save!
if@inputData.valid?
  render :status => 200, :json => "Data inserted successfully"
else
  render :status => 404, :json => "Not Inserted "
end

我已经定义了允许强参数方法允许这样的嵌套属性

I have defined permit strong parameter method allow nested attributes like this

def referral_params
params.require(:person).permit(:id, user_attributes: [:id, :first_name, :last_name, :email], device_attributes: [:id, :os_type, :os_version], location_attributes: [:id, :latitude, :longitude], duration_attributes[:id, :start_time, :end_time]) end

但我不确定如何将这个 regerral_params 方法与 JSON 输入字符串一起使用....

But I am not sure how to use this regerral_params method along with JSON input string....

推荐答案

您可以尝试将 referral_params 方法更改为:

You could try changing your referral_params method to this:

def referral_params
  json_params = ActionController::Parameters.new( JSON.parse(request.body.read) )
  return json_params.require(:person).permit(:id, user_attributes: [:id, :first_name, :last_name, :email], device_attributes: [:id, :os_type, :os_version], location_attributes: [:id, :latitude, :longitude], duration_attributes[:id, :start_time, :end_time])
end

方法中的第一行解析您的 JSON(如果我没记错的话,它会返回一个 Ruby 哈希值)并从中创建一个新的 ActionController::Parameters 对象.第二个在类似 params 的对象上使用 permitrequire.

The first line inside the method parses your JSON (which returns a Ruby hash, if I remember correctly) and creates a new ActionController::Parameters object from that. The second one uses permit and require on that params-like object.

params 通常是根据发布数据键/值对自动创建的,并且属于 ActionController::Parameters 类型.要使用permitrequire,您必须创建一个那个类从散列中手动.

params is usually automatically created from post data key/value pairs, and will be of the type ActionController::Parameters. To use permit and require, you have to create an object of that class manually from a hash.

要使用这些经过消毒的参数,您必须更改

To then use these sanitized params, you have to change

@inputData = Person.new(JSON.parse(data))

@inputData = Person.new(referral_params)

这篇关于强参数和 json 输入 rails 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆