0

I am new to rails, and am stuck with the following problem:

I need a persistent class variable (I think) for a human readable customer ID. The customer class is a subclass of a contact class in an Single Table Inheritance setup, so the database generated ID is not usefull as it is not linearly ascending.

I suppose I need a class variable or global variable to implement a kind of counter/id (it is not the count method as customers can be deleted). Am I correct? In this case the class variable needs to be saved somehow to the database, right?

I am a bit lost on

  1. how to save it
  2. when exactly to increment it: I have to override the new method, calling first super?
  3. how to load the value in case the application needs to be restarted at some point

.

Should I prefer a Multible Table Inheritence setup instead and use the database ID? That would be a pitty, as more than 90% of the fields in both classes are the same.

1 Answer 1

1

Why would your ID be linear? And why isn't it linear?

I think you went wrong somewhere but just in case i misunderstood you, you could add a migration (add a attribute 'generatedID' to your Customer table) and write a method, something like this:

def generateID
  if Customer.all.count == 0
   1
  else
    Customer.last.generatedID + 1
  end
end

Then when you save the Customer object:

@customer = Customer.new(params[:user])
@customer.generatedID = generateID
@customer.save!

BUT THIS IS REALLY A BAD APPROACH, you can allways read the id of the object and show it to a user, and i am really not sure that it wouldn't be linear.

Sign up to request clarification or add additional context in comments.

3 Comments

Your solution does not generate a unique ID. When the last Customer is deleted before the next one is created. It is for my client who wants to have easily recognisable IDs to quickly differentiate between customers. If I take the DB generated ID, that one is intermingled with IDs from the other contact objects. That is why they're not linear (to be honest I don't like the solution either)
I tried your solution, but it generates a DB error in the "all" call, during testing and I am totally lost: Client ActiveRecord::StatementInvalid: PGError: ERROR: missing FROM-clause entry for table "clients" LINE 1: ..." WHERE "contacts"."type" IN ('Client') ORDER BY clients.na... ^ : SELECT "contacts".* FROM "contacts" WHERE "contacts"."type" IN ('Client') ORDER BY clients.name DESC
obviously it looks for a table clients, while the table (STI) is called contacts but the type is clients... rails error?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.