开发者

assigning random url to a resource in rails 3

I need to ge开发者_JAVA技巧nerate 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.


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 


Patricks answer should work - but it only covers routing incoming requests. If you're still using the standard routes (eg topic_path) to create your links, it will still use the normal routes.

If you run rake routes, you should see the name of the route you created with with the random_id. (You may need to name it using :as => 'random_route')

If you call that instead of the standard topic_path you should get the route you are after

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜