Giovani Giovani - 1 year ago 52
Ruby Question

Populate field in db with another field

I have table "Products" and want to populate one column with data from another column, that:

Product.first.product_id == Product.first.barcode
Currently keeping the barcode in
is nil.

edit: I want to populate all Products barcodes with existing data from Product.product_id.

I've been trying to google that, but still don't know how should I migrate the data. Thanks for any help!

edit: I use PostgreSQL.

Answer Source

You can use ActiveRecord::Relation#update_all, to update the existing records in the database.

Product.update_all("barcode = product_id")

Since this is a one time job, it can be done using a Custom rake task.

For the future records, use a callback. In product.rb

before_save :update_barcode

def update_barcode
  self.barcode = self.product_id