2015-11-16 146 views
0

我有红宝石的rails应用程序和我的控制器应处理创建许多对象的请求。对象数据通过json使用POST方法从客户端传递。Ruby on Rails和JSON请求处理

我的请求的示例(记录从控制器):

Processing by PersonsController#save_all as JSON 

Parameters: {"_json"=>[{"date"=>"9/15/2014", "name"=>"John"}, 
     {"date"=>"9/15/2014", "name"=>"Mike"}], "person"=>{}} 

所以我需要保存这两个用户,但我有一些问题:

  1. 如何在这里验证强劲的参数?只有名称和日期属性可以从客户端传递
  2. 如何使用Person.new(params)将字符串转换为日期?
  3. 我可以以某种方式预处理我的json吗?比如我要替换NAME =“迈克”NAME =“迈克用户”,然后才通过它在我的模型
  4. 我希望通过添加一些默认参数,例如,以丰富每个人的参数,可以我想补充状态=“new_created”以人PARAMS

回答

1

首先我会名称的根PARAM像“用户”,那么它给出的所有连接到控制器名称和数据结构正在发送。

关于强参数。配置取决于你的Rails应用程序版本。 < = 3.x没有包括这个,所以你需要添加gem。如果你是> = 4.x,那么这已经是rails的一部分。

接下来在你的控制器中,你需要定义一个方法来过滤你需要的参数。我应该看起来像这样:

class PeopleController < ApplicationController 
    def some_action 
    # Here you can call a service that receives people_params and takes 
    # care of the creation. 
    if PeopleService.new(people_params).perform 
     # some logic 
    else 
     # some logic 
    end 
    end 

    private 

    def base_people_params 
    params.permit(people: [:name, :date]) 
    end 
    # Usually if you don't want to manipulate the params then call the method 
    # just #people_params 

    def people_params 
    base_people_params.merge(people: normalized_params) 
    end 
    # In case you decided to manipulate the params then create small methods  
    # that would that separately. This way you would be able to understand this 
    # logic when returning to this code in a couple of months. 

    def normalized_params 
    return [] unless params[:people] 

    params[:people].each_with_object([]) do |result, person| 
     result << { 
     name: normalize_name(person[:name]), 
     date: normalize_date(person[:date]), 
     } 
    end 
    end 

    def normalize_date(date) 
    Time.parse(date) 
    end 

    def normalize_name(name) 
    "#{name} - User" 
    end 
end 

如果您看到代码开始进入自定义进入服务。这将有助于帮助您保持控制器精简(和健康)。

当你在当时创建一个原因(而不是像这里那样的批处理)时,代码更简单一点,你使用散列而不是数组......但它几乎是相同的。

编辑:

如果您不需要操纵特定PARAM那么就不要

def normalized_params 
    return [] unless params[:people] 

    params[:people].each_with_object([]) do |result, person| 
    result << { 
     name: person[:name], 
     date: normalize_date(person[:date]), 
    } 
    end 
end 
+0

THX了很多,但如果我不需要normalize_name名而错过这一行,然后它从结果参数集中消失 –