Question

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

Was it helpful?

Solution

Add this route also:

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

OTHER TIPS

In routes.rb You can add

get "signup", to: "users#new"
post "signup", to: "users#create"
put "signup", to: "users#update"

And in Registration form - Check signup_path

form_for(resource, as: resource_name, url: signup_path, html: {method: 'post'})

For Other Readers who has used devise_for :users, can defined routes as:

devise_scope :user do
  get "signup", to: "devise/registrations#new"
  post "signup", to: "devise/registrations#create"
  put "signup", to: "devise/registrations#update"
end

And Registration form as above.

By adding this routes, you can use your named routes like (register, signup) even after user fills register form with some error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top