I’ trying to create a simple login form where users should be able to sign in. I want it to redirect to the users show action, but instead it redirects to .../sessions, I want it to redirect to `…/users/1. I have a session controller that looks like this (I have been following Rails Tutorial Book)
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
sign_in user
redirect_to user
else
render 'new'
end
end
I have tried to change redirect_to userto redirect_to users_path(user) but it doesn’t work.
My routes looks like this:
root :to => 'pages#home'
resources :users
resources :sessions, only: [:new, :create, :destroy]
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
And sessions/sessions.new.html.erb looks like this:
<%= form_tag sessions_path do %>
<%= text_field_tag :email, params[:email], :placeholder => "E-post" %>
<%= password_field_tag :password, nil, :placeholder => "Lösenord" %>
<%= submit_tag "Logga in" %>
<% end %>
My rails skills is a bit rusty, so it’s probably something basic.
Update
I managed to “solve” it by creating a index action in my session controller which redirect to the correct path when getting called. I don’t’ know (or think) this is the most optimal way to do it. The original problem was that when a user signed in, it for some reason got redirected to /sessions, and not the root path which I want. When or if the user updated the browser the application crashes (since I didn’t have a index action in my session controller). I don’t know why it isn’t redirecting to the right path, I did also try redirect_to user_path(user), but with the same result. Any tips on how to solve it the “right” way, would be great! I also had the same problem when users signed up, it redirected to /users instead of /.
It sounds like your action is falling to the else condition and consequently doing the render :action=>”new” and not the redirect you’re looking for. In the case of the render action, the url would show something like you’ve described “…/sessions” since the form is likely (and correctly) doing a POST to that url but has failed and is re-rendering without redirecting.
In other words, I think your user.authenticate(…) is probably failing or for some reason returning nil or false.
UPDATE:
Since you’re using jquerymobile, the page that you redirect to is being AJAXed in. The documentation (see the Redirects and linking to directories section) says that you can use a data-url attribute on the div that has the data-role as page to control the url. So, for your example, wrap the content in app/pages/home in a ‘page roled’ div tag with the data-url set for whatever you want…for example: