将JSON发布到模型

时间:2017-07-29 23:12:18

标签: ruby-on-rails

我正在将JSON传递给我的控制器创建方法。我试图将此JSON传递到我的模型/数据库中。但我一直收到错误:

When assigning attributes, you must pass a hash as an argument.

我没有传递哈希值吗?

JSON:

{
  "people": [
    {
      "name": "Tom",
      "sport": "Ski",
      "mood": "Happy",
      },
    {
      "name": "Robbie",
      "sport": "Swim",
      "mood": "sad",
      },
    {
      "name": "Ted",
      "sport": "Running",
      "mood": "Sleepy",
      },
  ]
}

控制器:

class PeopleController < ApplicationController
  respond_to :json
  def create
    new_record = people_params
    records = People.new(new_record)
    records.save
  end

  private

  def people_params
    params.permit(people: [:name, :sport, :mood]).require(:people)
  end 
end

架构:

  create_table "people", force: :cascade do |t|
    t.string   "name"
    t.string   "sport"
    t.string   "mood"
  end

1 个答案:

答案 0 :(得分:1)

在ActiveRecord中,new方法不会使用哈希数组,只需一个哈希值。而create确实允许一系列哈希,以创建多个模型。

所以你只需要改变

new_record = people_params
records = People.new(new_record)
records.save

records = People.create(people_params)

如果有任何内容无效,则不会保存任何内容,或者如果有任何内容无效,您可以使用create!引发错误