Reputation: 803
I'm having a lot of trouble understanding sessions and authentication with Rails. So basically, I tried to set a session based on user_id, following a tutorial from a book. Here is the create method in my sessions_controller.rb file:
def create
if user = User.authenticate(params[:email], params[:password])
session[:id] = user.id
redirect_to root_path, :notice => 'Logged in successfully'
else
flash.now[:alert] = "Invalid login/password combination"
render :action => 'new'
end
end
But, when I try to define a current_user method in my application_controller.rb file, it asks me to reference the session based on user_id:
def current_user
return unless session[:user_id]
@current_user = User.find_by_id(session[:user_id])
end
Here is what confuses me - user_id is an attribute of each Recipe (equivalent of articles or posts in my app) that creates a has_one relationship with a user. nowhere else in my application is user_id defined. so user_id shouldn't be an attribute of a User, right?
Just to clarify, I've listed the parameters for User objects and Recipe objects from the rails console:
2.0.0-p598 :019 > Recipe
=> Recipe(id: integer, title: string, body: text, published_at:
datetime, created_at: datetime, updated_at: datetime, user_id:
integer, photo_of_recipe_file_name: string,
photo_of_recipe_content_type: string, photo_of_recipe_file_size:
integer, photo_of_recipe_updated_at: datetime)
2.0.0-p598 :020 > User
=> User(id: integer, email: string, hashed_password: string,
created_at: datetime, updated_at: datetime, username: string)
Upvotes: 4
Views: 7338
Reputation: 3521
In your create method it should be
session[:user_id] = user.id
You are setting up a key :user_id
in the session hash and storing the authenticated user's id user.id
in it for later use
Key name can be anything
Upvotes: 7