How to handle unique urls in rails application?

I am building a web application to learn Ruby on rails. The application allows users to log in and draw on canvas. I want the user to be able to share a masterpiece using a uniquely generated URL specific to the user number. The cover creator should also be able to password protect the URL. I don't need a Facebook or LinkedIn sharing url, twitter or anything like that. Just select a simple URL that can be emailed or emailed, etc.

What approach should be used to implement this? Are there any gems that easily allow this functionality out of the box? Any advice on design and wisdom will be greatly appreciated. Thanks!

+4
source share
1 answer

You may have a boolean value in your masterpiece model called public. If the image is publicly available, it may be accessible to anyone. However, if it is not publicly available, then using your return URL will do nothing.

Your public url can be generated using a hash. I usually like to have a hash token created when creating the model.

rails g migration add_hash_token_to_masterpieces hash_token

In your model, you can use the before_create method to call a private method. taht will update your hash_token with randomized hex code.

  before_create :generate_hash_token private def generate_hash_token begin self.hash_token = SecureRandom.hex end while self.class.exists?(hash_token: hash_token) end 

Then in the routes file you can do something like this

match "/public/:hash_token" => "masterpieces#public_masterpiece", as: "public"

Then, in your controller, you can find the method of your hash token and have the appropriate view to display the image for the public user. The _and_public contains only those that are publicly available. Even if the hash is valid, it will not return a record if the masterpiece is not publicly available.

 def public_masterpiece @masterpiece = Masterpiece.find_by_hash_token_and_public(params[:hash_token], true) ... end 

Then, in your masterpiece views, you can have a file called public_masterpiece.html.erb , which is a specific render for users who do not yet have an authorized account but can still view the image. If you use a stone, such as cancan, for authorization, you need to make sure that you enable the public_masterpiece action.

+3
source

All Articles