0

I tried rails guide and searched a lot but can find that answer. I am trying generate secret post scaffold in rails 4 by using scaffold generator

Scenario is : users can create secret posts and they will get a link with secret token in future it works as a verification string

rails g scaffold secret title:string content:text token:string

I want to append that token value in all "secret_posts" routes

eg:

: secret/1/sadkljaldjlak 

: secret/1/edit/sasadadallkha


I want to use that token as unique code for verification . any help is appreciated

2
  • whay do you need to append it in routes ? You can send it through your url like edit_sectret_path(:token => @token)
    – Debadatt
    Jul 17, 2013 at 12:05
  • yeah , but its just not editing , link after creating secret post look like /secret/1/tokenada i mean they can save that link and its like editing updating posts without using password
    – Alok Yadav
    Jul 17, 2013 at 12:09

2 Answers 2

0

First, create a migration to chance token:string to token:text, then use the SecureRamdom.urlsafe_base64 to generate the token, use this code on your model:

def secret_token
   if self.new_record?
     self.token = SecureRandom.urlsafe_base64
   end
end

After that, you could create a route like this:

get   'secret/:edit_hash/edit',        to: 'secret#edit', as: :secret_offer
patch 'secret/:edit_hash',             to: 'secret#update'
put   'secret/:edit_hash',             to: 'secret#update'

and on your controller:

def edit
  @secret = Secret.find_by!(edit_hash: params[:edit_hash])
  your code..
end

def create
  @secret = Secret.find_by!(edit_hash: params[:edit_hash])
  your code..
end

hope this help

0

You should be able to do this by specifying the routes individually like this:

 get 'secret/:id/:token' => 'secret#show' #or whatever action

In that controller action you can ensure that the token matches the id.

But you should know that this is not secure, that url will be stored in browser history and will be visible to other sites if that page has external links

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.