Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I save multiple records at once in Rails?

Tags:

How would I save this array in one call with Rails?

tax_rates = [{
  :income_from => 0
  :income_to  => 18200
  :start => "01-07-2013"
  :finish => "30-06-2014"
  :rate => nil
  :premium => nil
  },{
  :income_from => 18201
  :income_to  => 37000
  :start => "01-07-2013"
  :finish => "30-06-2014"
  :rate => 0.19
  :premium => nil
  },{
    :income_from => 18201
    :income_to  => 37000
    :start => "01-07-2013"
    :finish => "30-06-2014"
    :rate => 0.19
    :premium => nil
    }]

Can I just call Rails.create(tax_rates)?

Also, is there a way to remove duplicate symbols so they look neater?

like image 313
Passionate Engineer Avatar asked Sep 29 '13 17:09

Passionate Engineer


People also ask

How do you create multiple records in Rails?

Here's a quick rundown of how to post multiple records embedded in an HTTP request with a single request: Update the strong params (or declare a new method) in the controller to accept an Array of data. Update the controller action (or declare a new one) to create records using create or create!

What does pluck do in Rails?

In Rails, pluck is a shortcut to select one or more attributes without loading the corresponding records just to filter out the selected attributes. It returns an Array of attribute values.

What is active record pattern in rails?

The Active Record Pattern is used to access the data stored in a relational database. It allows us to create, read, update, and delete data from a database. It is particularly used for persistently stored data. The Active Record Pattern is a part of the MVC design pattern.


2 Answers

Your example is almost correct.

Use ActiveRecord::Persistence#create, which can accept an array of hashes as a parameter.

tax_rates = [
  {
    income_from: 0,
    income_to: 18200,
    start: "01-07-2013",
    finish: "30-06-2014",
    rate: nil,
    premium: nil,
  },
  {
    income_from: 18201,
    income_to: 37000,
    start: "01-07-2013",
    finish: "30-06-2014",
    rate: 0.19,
    premium: nil,
  },
  # ...
]

TaxRate.create(tax_rates)  # Or `create!` to raise if validations fail
like image 108
Dennis Avatar answered Oct 20 '22 19:10

Dennis


A nice solution is to use the active record import gem. I recommend it over now built-in Rails bulk insert because it's more flexible in the options in case of constraint violation.

TaxRate.import(
  [:income_from, :income_to, :start, :finish, :rate, :premium],
  tax_rates
)

Its definitely better than my old answer which would trigger a db commit per entry in the array :)


Old answer:

tax_rates.map {|tax_rate| TaxRate.new(tax_rate).save } 

This way you'll retrieve an Array with true or false to know which did succeed and which didn't.

like image 39
apneadiving Avatar answered Oct 20 '22 20:10

apneadiving