Shawn Wilson Shawn Wilson - 1 year ago 64
Ruby Question

Trying to generate a Random String to Save to PG Table as client_number Rails 4, PGSQL

I am trying to generate a "Client Number" automatically when an admin generates a new client in our Rails 4 app.

I have read several articles on this but most are talking about breakable tokens.

so far my Client model only has a client_number attribute and it is a string.

my model looks like:

class Client < ActiveRecord::Base

before_save generate_client_number

validates_uniqueness_of :client_number

def generate_client_number
self.client_number = SecureRandom.hex(2).upcase


We are using PostgreSQL as our DB, I am relatively new to rails. after adding the above to our model, it errors out in the console this is the error it throws:

NameError: undefined local variable or method `generate_client_number' for #<Class:0x007fc59bdd7008>
Did you mean? generated_attribute_methods

I am a little bit lost as to where I am going wrong here. any assistance would be greatly appreciated, I am sure this is an oversight on my part. Thanks in advance.

EDIT #1:

The error has been eliminated by fixing the code error. And Adding

before_save :generate_client_number

however when I attempt to Create the random string and save to db I now get:

irb(main):013:0> Client.create
(0.1ms) BEGIN
Client Exists (0.2ms) SELECT 1 AS one FROM "clients" WHERE "clients"."client_number" IS NULL LIMIT 1
(0.1ms) ROLLBACK
=> #<Client id: nil, client_number: nil, created_at: nil, updated_at: nil>

Answer Source

It's just a matter of using a symbol correctly:

before_save :generate_client_number

These after_* and before_* hooks are defined by a symbol with the name of the method called, so you need to write :generate_client_number, with :, instead of just generate_client_number.

About the fact it is not generating a number, your error message implies your are getting a duplicate and having a roolback. I suggest you to try

self.client_number = SecureRandom.uuid.upcase
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download