0

我有一个 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

但数据没有保存。

有什么解决办法吗?

在用户下保存的嵌套属性:

{
    "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"
            }
        ]
    }
    ]
}
4

2 回答 2

2

如此处所示,我建议您使用此 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
于 2013-01-19T18:09:04.537 回答
0

好的,我看到您对已发布参数的编辑。所以在你的控制器中这样做:

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
于 2013-01-19T17:44:01.467 回答