Question

I am new to rails and I would like to know that if there is a way to change the name of the routes. I will explain the sentence in a minute. I have a controller named users_controller and below is the code that I have in my controller:

def create
  if @user.save
  redirect_to @user
end

And my routes.rb file is as below:

resources :users

get '/users/:id', to: 'users#show'

Now suppose I have a form and I fill it correctly then I will be redirected to localhost:3000/users/id(id = some value) which I do. Now I want this URL to be like localhost:3000/registered . That is when i click the submit button and if everything is correct I wanted to see the URL as localhost:3000/registered which takes me to my show action or which works just like localhost:3000/users/id(id = some value). I don't want the ID to be visible.

For this I tried get 'registered', to: 'users#show' but still I see the same URL as localhost:3000/users/id(id = some value). Please tell me how to do this.

And here is my show action

def show

@user = User.find(params[:id])

end

I tried another way by making another action into the same controller. I made index action in my users_controller and executed then I got a No method Error

Was it helpful?

Solution 2

At last, from the discussions I had it has been cleared that there is no way to hide your ID, but we can change the way they appear on the browser. One and suggested way is to create a hash for the ID and use it to display the item in show action or the other way is to redirect your action to some static page.

OTHER TIPS

Just use your routing as:

match "/registered", :to => "users#show", :as => :user_registered, via: :get

to use this path you will use

redirect_to user_registered_path(id: user_id) 

in your method.

You need to change your redirect_to in your user controller's create and update actions.

class UsersController < ApplicationController
  def create
     # get user from params
    if @user.save
      redirect_to registered_path
    else
      render :new
    end
  end

  def update
     # get user from params
    if @user.save
      redirect_to registered_path
    else
      render :edit
    end
  end
end

EDIT: As we discussed in the comments, you don't want to use "users#show", since the registered page will look the same for every user. You can make your own registered controller to do this.

rails g controller registered index
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top