【问题标题】:How can I create with base64 tokens automatically for my products?如何为我的产品自动创建 base64 令牌?
【发布时间】:2016-08-10 19:35:49
【问题描述】:

我使用 ruby​​ on rails 进行构建,我想为我的模型自动生成唯一的 Base64 令牌。在我见过的所有示例中,令牌都是为名称或密码生成的。一般如何生成令牌?

我的模型看起来像这样:

{        
  "id": 2,
  "name": "cookies",
  "description": "box 150g",
  "logo_url": null,
  "token": null
}

【问题讨论】:

  • 你需要这个令牌做什么?阅读before_create activerecord 钩子。

标签: ruby-on-rails ruby


【解决方案1】:

您可以使用 SecureRandom#urlsafe_base64 简单地生成一个随机的 URL 安全 base64 字符串并填充 token 字段。

before_create :generate_token

def generate_token
  self.token ||= SecureRandom.urlsafe_base64
end

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2020-07-22
    • 2020-08-29
    • 2018-05-18
    • 2020-10-15
    相关资源
    最近更新 更多