ruby-on-rails

using has_secure_token with existing record in rails


I am new to rails trying to understand has_secure_token I want token to be generated for all the existing and new groups and want to set expiry of two weeks and regenerate it every two weeks...

has_secure_token looked very good at a first sight, I am using it in my groups model to generate token as::

has_secure_token :group_token 

it creates token on newly created groups and existing group has blank rows..


Solution

  • Yup as you said has_secure_token has the issue that for existing entities the row keeps empty, that's because the secure token is generated during a before_create callback, for existing entities you can use something like this to get the token of any entity (old or new ones):

    def get_group_token 
      self.regenerate_group_token if self.group_token.nil?
      self.group_token
    end
    

    define the function above inside your model class, of course, hope this helps you 👍

    The approach above trigger some callbacks and validations, in case you want to skip those this is another approach using the update_column method:

    def get_group_token 
      self.update_column(:group_token, SecureRandom.base58(24)) if self.group_token.nil?
      self.group_token
    end
    

    hope helps! 👌

    docs for update_column: http://apidock.com/rails/ActiveRecord/Persistence/update_column