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
end

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 : 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)

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