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

查看:101
本文介绍了强大的参数和json输入轨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对象.第二个在类似参数的对象上使用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输入轨4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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