How to use Rails with PostgreSQL to set custom serial numbers using custom rules

I would like to set a rule to automatically generate a serial number. I am using PostgreSQL. There are two tables; Store and Storerecord. Store = [id, code], Storerecord = [id, Store_code, no]

Today I have a store and the code is "A01". I would like to set the rule as A01 + date + N or A01 + random number.

If I need a format like this, how do I go about zipping this target? Thank!

+3


source to share


1 answer


You should add a callback after_commit

to your model (unless you have a specific reason to have the serial number generation code in the database itself).

So, you do something like this in your app /models/store.rb :

class Store < ActiveRecord::Base
  # Using after_commit, because we want to use ID of the record,
  # and it will be there only after record is saved to DB already
  after_commit :set_serial_number

  # other stuff you have in your model

  private

  def set_serial_number
    self.update_column(serial_number, self.id.to_s + self.code.to_s)
  end
end

      



A similar thing for your second model:

class Storerecord < ActiveRecord::Base
  belongs_to :store

  after_commit :set_serial_number

  # other stuff you have in your model

  private

  def set_serial_number
    self.update_column(serial_number, self.store.id.to_s + self.no.to_s)
  end
end      

      

0


source







All Articles