Ruby On Rails : ActiveRecord : Batch update : Updating Multiple records at the same time

Sometime you may require to update multiple rows in your tables with a single HTTP request.

 # Updating multiple records:
  people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
  Person.update(people.keys, people.values)

This update method is a class method defined in ActiveRecord base class. Its different from the update method in following example

 # Updating multiple records:
  @person = Person.find(params[:id])
  @person.update(person_params)

Example above describes batch updates however if you need to query db for batches of records you can refer to this link  http://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-find_in_batches

For batch create

# Create a single new object
User.create(:first_name => 'Jamie')

# Create a single new object using the :admin mass-assignment security role
User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)

# Create a single new object bypassing mass-assignment security
User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)

# Create an Array of new objects
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])

# Create a single object and pass it into a block to set other attributes.
User.create(:first_name => 'Jamie') do |u|
  u.is_admin = false
end

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
  u.is_admin = false
end

One thought on “Ruby On Rails : ActiveRecord : Batch update : Updating Multiple records at the same time

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s