after finishing Michael Hart’s tutorial on rails, I’m giving making a simple app of my own a try.
I managed to create the users resource, and am now trying to create a sessions resource, to track when someone is logged in. I’m getting some really wacky results.
1) I was trying to display different menu options for when someone is logged in, and for when someone is logged out. It works, except it behaves the opposite to the way I expected it ! i.e when I write
<ul class="nav pull-right">
<% if signed_in? %>
#menu for registered users
<% else %>
#menu for unregistered users
<% end %>
</ul>
When I’m logged in, the #menu for unregistered users shows up, and when I’m logged out, the #menu for registered users shows up.
2) I’m also trying to create a link to the user’s admin page, which is the basically the user’s id page.
I put this as the following as the link code
<%= link_to "Admin", user_path(current_user) %>
And got the error
No route matches {:action=>”show”, :controller=>”users”, :id=>nil}
This makes me think that the current_user I defined in the sessions helper is not being saved, but than I think, but I’m not sure why.
Here’s the code I have for the
User Model
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
Sessions Controller
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to user
else
flash.now[:error] = 'Invalid Email/Password Combination' #Not quite right;
render 'new'
end
end
end
SessionsHelper
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
end
ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
Thoughts?
Thanks for the help guys! It seemed like I had two errors — 1) I didn’t sign in users when they registered in the users controller and 2) I didn’t restart the server, and do a db:reset. After trying that, the other problems, having to do with the signout not working, fixed.