Reputation: 8699
I have different models like Customer, User, Admin etc in my rails app. I would like to make the primary id as string and prepend it with a character. so for customers, the id would be something like C1, C2, C3. For Users it will be U1, U2, U3 etc..
Upvotes: 0
Views: 184
Reputation: 94
You can declare an alternative id column or you can define your own key.
for example:
class Customer < ActiveRecord::Base
self.primary_key = "C_"+ #your column
end
Upvotes: 0
Reputation: 33954
If you really need this info, you could just define a method called string_id
or something that returns the numerical id
prepended with a custom prefix that you define?
Comparison of non-numerical primary keys (when finding records in your DB) is only going to slow down your app, and I'm not sure why you would want to do this since you can simply do a .class.name
call on the model of your choice to get the class name back, or the first character of the class, or whatever. I think you need to justify and explain the technical need for this in your question a bit more, otherwise it just looks like a really bad idea.
Also, your question title specifies "random" - but where's the random part? What is it you're trying to do exactly?
Basically there are multiple, better ways to do this than trying to use a String as your primary key, at least based on what information you've provided in your question thus far.
Upvotes: 2
Reputation: 211590
Unless you have a really, very, super good reason for doing this, just don't. Generating your own keys seems like a great idea until it causes a malfunction.
Instead, create an auxiliary key with a unique index and use it for this purpose.
Upvotes: 2