Ruby on rails 是否检查Rails API中JSON的格式?

Ruby on rails 是否检查Rails API中JSON的格式?,ruby-on-rails,json,api,Ruby On Rails,Json,Api,我正在用Rails 4设计一个API,现在我的Orders控制器的创建操作有以下内容: def create begin @order = @api_user.orders.create!(order_params) render :json => @order, :only => [:id], :status => :created, :location => @order rescue render :json =&

我正在用Rails 4设计一个API,现在我的Orders控制器的创建操作有以下内容:

def create
    begin
      @order = @api_user.orders.create!(order_params)
      render :json => @order, :only => [:id], :status => :created, :location => @order
    rescue
      render :json => {}, :status => :unprocessable_entity
    end
  end
这样,我要求用户发送一个JSON,如下所示:

{"order" : {"description_1" : "Neque porro quisquam", "description_2" : "Neque porro quisquam", "types_attributes" : [{"url" : "http://test.com"}]}}
所以,我要做的就是检查参数:

params.require(:order).permit(:description_1, :description_2, {types_attributes: [:url]})
我的问题是:

如果我想避免用户必须在JSON参数中指定“order”键,我将如何调用create操作?我需要做
orders.create!(键1:params[:键1],…)


解决此问题的常用方法是什么?

如果
参数包含
订单的属性,则只需使用:

@order = @api_user.orders.create!(params)

但是,检查这些参数是否存在可能的格式错误的方法?或者我应该尝试创建它吗?我将依靠您的强参数设置和AR验证来检查数据。如果这些失败(使用create!),您将得到一个异常。假设我想让用户给我一个关联的ID,显然我需要获取这些ID并确保它们存在于数据库中。那么检查JSON是有意义的,对吗?是的,那会很聪明。不过,我会通过自定义验证来实现这一点,以便将逻辑与其他验证整合到您的模型中。如果其中一个ID无效,您可以检查是否存在关联ID,并将其添加到错误哈希(
:base
或association)。