Sidekiq : Is too fast; Record not found

“Cannot find ModelName with ID=12345”

Sidekiq is so fast that it is quite easy to get transactional race conditions where a job will try to access a database record that has not committed yet. The clean solution is to use after_commit: Continue reading


3.3 Changing Tables

3.3 Changing Tables

A close cousin of create_table is change_table, used for changing existing tables. It is used in a similar fashion to create_table but the object yielded to the block knows more tricks. For example:

change_table :products do |t|
  t.remove :description, :name
  t.string :part_number
  t.index :part_number
  t.rename :upccode, :upc_code

removes the description and name columns, creates a part_number string column and adds an index on it. Finally it renames the upccode column.

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

Sometime you may require to update multiple rows in your tables with different data. If you were looking for updating all record with same data then you should go for update_all method.

Batch update

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

Continue reading

Ruby On rails: Assign values from form to Model object but not save

Yes we can update a new Model object with values from a form saved in params without hitting to database.

# Assuming that params contains data from the form
# model_params is a private method that checks if only permitted columns
# are fetched and returns the fields as Hash

newObj = Model.find params[:id]
newObj.assign_attributes model_params

Note: update_attributes = assign_attributes + save