Reputation: 389
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
.
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
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