title: Sessions and user_id in rails
body: <p>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:</p>
  
  <pre><code>def create
  if user = User.authenticate(params[:email], params[:password])
    session[:id] = user.id
    redirect_to root_path, :notice =&gt; 'Logged in successfully'
  else
    flash.now[:alert] = "Invalid login/password combination"
    render :action =&gt; 'new'
  end
  </code></pre>
  
  <p>end</p>
  
  <p>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:</p>
  
  <pre><code>def current_user
    return unless session[:user_id]
    @current_user = User.find_by_id(session[:user_id])
  end
  </code></pre>
  
  <p>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?</p>
  
  <p>Just to clarify, I've listed the parameters for User objects and Recipe objects from the rails console:</p>
  
  <pre><code>    2.0.0-p598 :019 &gt;   Recipe 
      =&gt; 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 &gt; User
      =&gt; User(id: integer, email: string, hashed_password: string,     
      created_at: datetime, updated_at: datetime, username: string)
  </code></pre>