Kostas Georgokitsos
Kostas Georgokitsos

Reputation: 389

rails persistent class variable

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.

Upvotes: 0

Views: 328

Answers (1)

Zippie
Zippie

Reputation: 6088

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.

Upvotes: 1

Related Questions