如何一次发布所有数据?

时间:2013-01-19 17:32:49

标签: ruby-on-rails ruby

我有一个Rails 3应用程序试图一次发布一组用户。我想通过Postman REST客户端发帖。如果我一次尝试发布单个用户,则效果很好,但一次不能发布多个用户。

这是我的用户模型:

class User < ActiveRecord::Base
  attr_accessible :name,age,email,mobile,gender
end

我的用户控制器:

respond_to :html , :json

def create
  @user = User.new(params[:user])
  if @user.save
    render :json => { :status => :ok, :message => "User Created Successfully"}.to_json
  end
end

用户以多种用户的JSON格式发布数据:

{
  user:[
    {
      "name":"abc",
      "age": 23,
      "email": "abc@gmail.com",
      "mobile": 9876543210,
      "gender":"M"
    },
    {
      "name":"def",
      "age": 26,
      "email": "def@gmail.com",
      "mobile": 9876543210,
      "gender":"F"
    }
  ]
}

是否可以在Rails中执行此操作?

我试过了:

def create
  @userlist = User.new(params[:user])
  @userlist.each do |u|
    u.save
  end
  render :json => { :status => :ok, :message => "User Created Successfully"}.to_json
end

但数据未保存。

有没有解决方案?

在User下保存嵌套属性:

{
    "users" :[
    {
        "name":"abc",
            "age": 23,
            "email": "abc@gmail.com",
            "mobile": 9876543210,
            "gender":"M",
            "projects":
                [
                {
                    "projectname":"abc",
                    "type":"abc"
                },
                {
                    "projectname":"def",
                    "type":"abc"
                },
                {
                    "projectname":"ghi",
                    "type":"abc"
                }
        ]
    },
    {
        "name":"def",
        "age": 26,
        "email": "def@gmail.com",
        "mobile": 9876543210,
        "gender":"F",
        "projects":
            [
            {
                "projectname":"abc",
                "type":"abc"
            },
            {
                "projectname":"def",
                "type":"abc"
            },
            {
                "projectname":"ghi",
                "type":"abc"
            }
        ]
    }
    ]
}

2 个答案:

答案 0 :(得分:2)

here所示,我建议您使用this gem批量插入(取决于一次传递的可能用户数量):

def create
    users = []
    @userlist = params[:users]

    @userlist.each do |u|
       user = User.new(u)
       users << user
    end

    User.import(users)

    render :json => { :status => :ok, :message => "User(s) Created Successfully"}
end

答案 1 :(得分:0)

好的,我看到了你发布的params的编辑。所以在你的控制器中这样做:

def create
    @userlist = params[:users]
    @userlist.each do |u|
       user = User.new(u)
       user.save!
    end
    render :json => { :status => :ok, :message => "User Created Successfully"}.to_json
end