Question

i am fairly new to rails and want to keep the url the same for a user signing in if there is an error and the 'new' template is rendered

here are my routes

resources :users, only: [:new, :create]
resources :sessions, only: [:new, :create, :destroy]

root to: 'pages#home'

match '/signin', to: 'sessions#new'
#match '/signin', to: 'sessions#create', via: :post, as: :post_session
match '/logout', to: 'sessions#destroy'

and here is the sessions controller code

def new
end

def create
    user = User.find_by_email(params[:session][:email])
    if user && user.authenticate(params[:session][:password])
        sign_in user
        redirect_to root_url
    else
        flash.now[:error] = 'Invalid email or password'
        render 'new'
    end
end

as you can see,i have a custom route commented out to catch the post so that the render 'new' call keeps the /signin url, but when i do this, the flash messaging of an error does not render in the page (it does without that route though). i tried to use flash without the now method and still was not seeing my message show up. any ideas?

EDIT:

i tried the suggestions below and was still seeing the issue. after looking at the access logs, the application was routing to the first signin route because it was defined with match and not get. my updated and working routes file now looks like this

resources :users, only: [:new, :create]
#resources :sessions, only: [:new, :create, :destroy]

root to: 'pages#home'

match '/signin', to: 'sessions#new', via: :get
match '/signin', to: 'sessions#create', via: :post, as: :post_session
match '/logout', to: 'sessions#destroy', via: :delete
Was it helpful?

Solution

Take out the now, that shouldn't be needed. Your routes are probably conflicting. Based on how you have the match lines setup, you can probably just remove the resources :sessions altogether, and then uncomment the match line. That should take care of what you need.

Also, make sure to go back to your other questions and accept some answers. A 0% acceptance rate isnt as likely to attract answers.

Edit

Based on your comments, it might just not know what to render at this time when you removed the resources call. Try changing to:

render "sessions/new"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top