Batch insertion in rails 3

前端 未结 4 1316
臣服心动
臣服心动 2020-12-04 16:44

I want to do a batch insert of few thousand records into the database (POSTGRES in my case) from within my Rails App.

What would be the \"Rails way\" of doing it? So

4条回答
  •  生来不讨喜
    2020-12-04 17:26

    You can create a script in your rails model, write your queries to insert in that script In rails you can run the script using

    rails runner MyModelName.my_method_name
    

    Is the best way that i used in my project.

    Update:

    I use following in my project but it is not proper for sql injection. if you are not using user input in this query it may work for you

    user_string = " ('a@ao.in','a'), ('b@ao.in','b')"
    User.connection.insert("INSERT INTO users (email, name) VALUES"+user_string)
    

    For Multiple records:

    new_records = [
      {:column => 'value', :column2 => 'value'}, 
      {:column => 'value', :column2 => 'value'}
    ]
    
    MyModel.create(new_records)
    

提交回复
热议问题