rails4 change default url xxx.com/new_page to xxx.

2019-08-03 22:19发布

问题:

I used rails4.2.8 and ruby2.5.0, when signup the new user , I set the new page jump to http://127.0.0.1:3000/email_confirm ,but now I want to change the url to http://127.0.0.1:3000/email_confirm/username, that is I want to add username to the default url, How could I to rewrite the codes? Thanks for your help so much~~

the controllers/user_controller.rb codes like this :

def create
    @user = User.new(user_params)  
    if @user.save
      log_in @user
      flash[:success] = "almost success!"
      redirect_to :email_confirm
    else
      flash.now[:danger] = 'fail to signup!'
      render :new
    end
  end

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

the routes.rb codes like this:

get 'signup'  => 'users#new'
get 'login'   => 'sessions#new'
get 'profile' => 'users/show'
get 'email_confirm' => 'users#email_confirm'
post 'login'   => 'sessions#create'
delete 'logout'  => 'sessions#destroy'
resources :users

And email_confirm.html.erb in app/views/users/email_confirm.html.erb

回答1:

In your routes.rb, change:

get 'email_confirm' => 'users#email_confirm'

to:

get 'email_confirm/:username' => 'users#email_confirm', as: 'confirmation'

Then, once the user signs up successfully, redirect_to confirmation_path(@user.username)