ruby-on-railscontrollerroutesrenderactionnamed-routing

Rendering rails named route


How do I render a rails named route properly from controller?

routes.rb:

get "logout" => "sessions#destroy", :as => "logout"
get "login" => "sessions#new", :as => "login"
get "signup" => "users#new", :as => "signup"

root :to => "home#index"

resources :users
resources :sessions
resources :likes

user_controller.rb:

def new
  @user = User.new
end

def create
  @user = User.new params[:user]
  if @user.save
    login(params[:user][:email], params[:user][:password])
    redirect_to root_url, :notice => "Welcome! You have signed up successfully."
  else
    render :new
  end
end

Problem is: the signup page is on /signup and when the data in @user is not filled out properly and render :new is called, instead of going to the url /signup it goes to /users. I would use redirect_to but id prefer not to because I want the errors saved off on the page to tell the users which data was not provided.

Update after added match "signup" => "users#create", :via => "post"

root             /                            {:controller=>"home", :action=>"index"}
users     GET    /users(.:format)             {:action=>"index", :controller=>"users"}
          POST   /users(.:format)             {:action=>"create", :controller=>"users"}
edit_user GET    /users/:id/edit(.:format)    {:action=>"edit", :controller=>"users"}
user      GET    /users/:id(.:format)         {:action=>"show", :controller=>"users"}
          PUT    /users/:id(.:format)         {:action=>"update", :controller=>"users"}
          DELETE /users/:id(.:format)         {:action=>"destroy", :controller=>"users"}
signup    GET    /signup(.:format)            {:action=>"new", :controller=>"users"}
          POST   /signup(.:format)            {:action=>"create", :controller=>"users"}

Thanks


Solution

  • Add this route also:

    match "signup" => "users#create", :via => "post"