I have a batch-add page for users that needs to auto-generate a unique
login name for each user. What i want to do is set their login name to
be “#{first_name}_#{id}”. The problem is - i can’t see the id until i
save the object, but i don’t want to save it until i’ve set the login.
Is there any way around this? Can i start creating an object and tell
it to use the id that will created when it’s saved? Or do i need to
save it, get the id and then save it again?
I have a batch-add page for users that needs to auto-generate a unique
login name for each user. What i want to do is set their login name to
be “#{first_name}_#{id}”. The problem is - i can’t see the id until i
save the object, but i don’t want to save it until i’ve set the login.
There is no id until you save it to the database. Rails (and any other
application) cannot tell what the next available id in the database will
be.
You could try to determine the highest used id in the database table and
increment this id but this does not guarantee that this id id is not
used
by another user in the meantime and is no more available.
Hi,
There is one filter called “after_save”, it will invoke a method
(let’s say a foo method) after model.save! succeed (here, you already
know the id). I figure you can use the foo method to update the login
name"#{first_name}_#{id}" column in database.
However, I still take this is somehow wired… it updates database
twice… unless you really have the reason to do this.
P.s. I dont think there is a good way to know the id beforehand unless
you really stored this user, cuz even you are able to know the last id
in database, you still cant guarantee that there is nobody
registering just one second before you!
Hi,
There is one filter called “after_save”, it will invoke a method
(let’s say a foo method) after model.save! succeed (here, you already
know the id). I figure you can use the foo method to update the login
name"#{first_name}_#{id}" column in database.
Thanks myst_tt, i don’t want to use a callback because the situation’s a
little more complicated than i described: by default, user’s logins are
set the same as their email address, but emails aren’t forced to be
unique (since a group of users can share an email). So, i actually only
need to autogenerate a login some of the time (a minority of cases
actually).
What i’ve ended up doing (and it seems dirty) is make a temporary
probably-unique login by combining first name and time since epoch in
microseconds - rails/mysql is unlikely to ever manage 2 transactions in
one microsecond so this should be fine. Then, after saving, i call
update_attributes to set it to firstname+id, which is guaranteed to be
unique and also more memorable than firstname+microseconds_since_epoch.
Like i say, i’m not very happy with this though.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.