I have a field in my User model called unique_identifier
which I want to populate with the outcome of the create_unqiue_identifier
method below.
How can I add this to the database for the user?
class User < ApplicationRecord
has_secure_password
def create_unique_identifer
loop do
self. unique_identifier = SecureRandom.hex(5) # or whatever you chose like UUID tools
break unless self.class.exists?(:unique_identifier => unique_identifier)
end
// add something here to store unique_identifer to the database?
end
end
I have figured this out, I have to return the result of create_unique_identifier
back to my controller. Then within the controller I can save the unique_identifier
for the User.
def create_unique_identifer()
loop do
self. unique_identifier = SecureRandom.hex(5) # or whatever you chose like UUID tools
break unless self.class.exists?(:unique_identifier => unique_identifier)
end
unique_identifier
end
to save I then added the below code to my controller:
if @user.unique_identifier.nil?
unique_identifier = @user.create_unique_identifer
@user.update(unique_identifier: unique_identifier)
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.