I try to construct a username based on name given. Since many people are named “John” I need to somehow check for this and create it by following a +1 count.
I’m a bit lost in how to iterate ActiveRecord to find in this case a username called john, then if already exists try john1 and if not available try john2 and so on. I can suppose it would use while but I have no idea how to iterate it for this case.
Any idea how to do this?
In order to not make multiple trips to the database, get a list of users that match the name, check the count of users, append the count to the name, and then check the already loaded collection for the new name.
It would look something like this:
Since you’re calling
to_aon theActiveRecord::Relation, you don’t have to worry about accidentally sending multiple queries to the database, since it is being converted to a standard Ruby array.