Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning random url to a resource in rails 3

I need to generate a random url to my Topic model(for example) as such:

http://localhost:3000/9ARb123

So how can I do this in rails?

Note: the random string must contain digits, small and capital letters.

like image 271
iosgcd Avatar asked Oct 12 '22 07:10

iosgcd


1 Answers

Something like this perhaps

#config/routes.rb
match "/:random_id" => "topics#show", :constraints => {:random_id => /([a-zA-Z]|\d){3,6}/}

will match a random string of 3-6 random letters/numbers to the show method of your Topics controller. Make sure to declare other resources above this matcher, as something like "http://localhost:3000/pies" will route to Topics#show instead of Pies#index.

To generate a random url for your Topic you can go something like this:

#app/models/topic.rb
before_create :generate_random_id

def generate_random_id
   #generates a random hex string of length 6
   random_id = SecureRandom.hex(3)
end 
like image 153
Patrick Robertson Avatar answered Oct 20 '22 13:10

Patrick Robertson