JSON解码参数问题

the*_*he_ 6 ruby postgresql json ruby-on-rails

我有一个使用的rails 4应用程序postgresql.我还有一个backbone.jsJSON推送到rails 4 app的应用程序.

这是我的控制器:

def create
 @product = Product.new(ActiveSupport::JSON.decode product_params)

 respond_to do |format|
  if @product.save
    format.json { render action: 'show', status: :created, location: @product }
  else
    format.json { render json: @product.errors, status: :unprocessable_entity }
  end
 end
end
def product_params
  params.require(:product).permit(:title, :data)
end
Run Code Online (Sandbox Code Playgroud)

我正在尝试解析JSON并插入产品,但在插入时,我收到错误:

TypeError (no implicit conversion of ActionController::Parameters into String):

谢谢大家的帮助!

dim*_*rvp 8

你的里程可能会有所不同,但我通过像这样的绑定代码修复了一个微笑的问题:

hash = product_params
hash = JSON.parse(hash) if hash.is_a?(String)
@product = Product.new(hash)
Run Code Online (Sandbox Code Playgroud)

我遇到的特殊问题是,如果我只是在JSON.parse包含我想要创建的对象的参数上,我在单元测试时遇到了这个错误,但是当我的Web表单提交数据时代码工作得很好.最终,在记录了各种愚蠢的事情后丢失了1个小时后,我意识到我的单元测试以某种方式以"纯粹"的形式传递请求参数 - 即,对象Hash已经是,但是当我的webforms(或无头手动)通过cURL测试确实对数据进行了求和,参数就像你期望的那样 - 一个哈希的字符串表示.

当然,使用上面的这个小代码片段是一个bandaid,但它提供了.

希望有所帮助.