views:

602

answers:

3

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...)

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

...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.

+3  A: 

There's a plugin that should do what you want:

http://codesnipers.com/?q=using-uuid-guid-as-primary-key-in-rails

(All apologies to the SO censors for not pasting in the entire article. In my defense, it's loaded with links and formatting that would require quite a bit of effort to replicate. Not to mention that we'd be robbing the page's author of traffic and potential revenue.)

runako
I don't hear anyone complaining about your link.
drizzle
With this plugin, what happens when you create the model via a nested model form? I mean, if I have a create product form where you can add images as nested models will the images store the correct product_id?
tybro0103
+1  A: 

An alternative is to generate a token or checksum or whatever in a second column during record creation, and in all cases your controllers query for an object, use Model.find_by_id_and_token.

You'll then always generate URLs that contain and require both the id and token.

kch
The other reason to do it this way (adding a token/checksum) is that ActiveRecord is simply easier when the primary keys are integers -- as far as associations are concerned.
Philip Hallstrom
+1  A: 

The thing that is going wrong here is that self.id requires an int and OpenSSL::Digest.SHA1.hexdigest(UUID.timestamp_create()) returns a string with non-numeric characters which would lead to the value '0' being actually stored in the database

Gaurav