Reputation: 97
I have a user model that is associated with devise. This takes care of sign in/ sign up I have a userinfo model has name, email, gpa, major, college and token. As soon as the user signs up, they have to fill a form where they fill in all the information in the userinfo model other than the token.
What I want to do is assign a random five number integer to the user as soon as they sign up. This will be stored in token. So for example, in the form, the user fills out their name as "Jason", email as "[email protected]", gpa as "4.0", college as "Somewhere university". Thats all they fill out. That's all they will see. Then the program will assign a random five digit number to token, maybe "16352". Then I will be able to find that user by that token later on. So if someone enters "16352" in the index page under the "find user by token" area, this user will show up. How can I do that?
Upvotes: 2
Views: 205
Reputation: 14900
If you're using Rails 5 you can take advantage of a new feature called like this
class SomeModel < ApplicationRecord
has_secure_token :random_token
...
end
It will get generated on creation so you don't have to do much except of course have a column in your table called random_token
or whatever you want to call it.
The advantage of this over a simple random number is that this is not guessable and would take an astronomical amount of (bad) luck to guess.
You can read more about this nice feature here
Upvotes: 2
Reputation: 33420
You can use a before_save
callback, which sets a random number for an specific attribute for that model before being saved to the database.
In your model you can define it as set_random_number
or any number, and call it as before_save :set_random_number
:
before_save :set_random_number
def set_random_number
self.random_number = rand(10000..99999)
end
Then, whenever you create a new record for that model, the set_random_number
callback will "fire" before the record be saved, and will set a random number between 10000 and 99999.
Upvotes: 2