views:

87

answers:

2
+1  Q: 

authlogic in Rails

Hello,

I am using the authlogic gem for authentication. I have followed the steps at: http://railscasts.com/episodes/160-authlogic

I have the following code:

# config/environment.rb
config.gem "authlogic"

# models/user.rb
acts_as_authentic

# users_controller.rb
def create
  @user = User.new(params[:user])
  if @user.save
    flash[:notice] = "Registration successful."
    redirect_to root_url
  else
    render :action => 'new'
  end
end

def edit
  @user = current_user
end

def update
  @user = current_user
  if @user.update_attributes(params[:user])
    flash[:notice] = "Successfully updated profile."
    redirect_to root_url
  else
    render :action => 'edit'
  end
end

# user_sessions_controller.rb
def create
  @user_session = UserSession.new(params[:user_session])
  if @user_session.save
    flash[:notice] = "Successfully logged in."
    redirect_to root_url
  else
    render :action => 'new'
  end
end

def destroy
  @user_session = UserSession.find
  @user_session.destroy
  flash[:notice] = "Successfully logged out."
  redirect_to root_url
end

# application_controller.rb
filter_parameter_logging :password

helper_method :current_user

private

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

# config/routes.rb
map.login "login", :controller => "user_sessions", :action => "new"
map.logout "logout", :controller => "user_sessions", :action => "destroy"

I got it all working, except I would like to have a user_id in session so I can track which user posted which post, where should I set it?

+1  A: 

You should have the authenticated user's id in session["user_credentials_id"]

Jeff Paquette
+1  A: 

Why not just use the ID from the current_user helper method?

Like: current_user.id

Ben
Thank you @Ben that way what I way looking for.
Adnan