如何使 Rails 中的模型 ID 不可预测和随机 [英] How to make model IDs in Rails unpredictable and random

查看:26
本文介绍了如何使 Rails 中的模型 ID 不可预测和随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 rails 应用程序,从本质上讲,它不能要求用户注册,因此不能使用身份验证作为保护记录的常用方法.(我知道,我知道...)这里的用户信息仅限于电子邮件地址.所以我确实需要一种方法让我的模型 ID 不可预测,这样其他 ID 就不容易被猜到.(我知道,我知道...)

I'm writing a rails app that, by its nature, CANNOT require users to register, and thus cannot use authentication as the usual means to protect records. (I know, I know...) User information here is limited to email addresses. So I do need a way to make my model IDs unpredictable so that other IDs cannot be easily guessed. (I know, I know...)

我曾尝试使用 uuidtools 等插件在创建记录时随机化 id,如下所示:

I have tried using plugins like uuidtools to randomize ids as records are created, like so:

require 'uuidtools'
class Post < ActiveRecord::Base 
 def before_create() 
  self.id = OpenSSL::Digest.SHA1.hexdigest(UUID.timestamp_create()) 
 end 
end 

...一开始看起来不错,但有趣的事情发生了.ActiveRecord 有时会尝试在 id 中插入一个 0 值,但我收到诸如找不到 id=0 的帖子"等错误...

...This looks good at first, but funny things happen. ActiveRecord sometimes tries to insert a 0 value into the id and I get errors such as 'can't find Post with id=0' etc...

我的想法已经用完了.任何人都可以帮忙吗?谢谢.

I've run out of ideas. Can anyone help? Thanks.

推荐答案

在您的模型中,执行以下操作:

In your model, do this:

before_create :randomize_id

...

private
def randomize_id
  begin
    self.id = SecureRandom.random_number(1_000_000)
  end while Model.where(id: self.id).exists?
end

这篇关于如何使 Rails 中的模型 ID 不可预测和随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆