<repo_name>edlingao/members-only<file_sep>/app/helpers/sessions_helper.rb
module SessionsHelper
    def log_in(user)
		session[:user_id] = user.id # automatically encrypted
	end

	def remember(user)
		user.remember # user model method
		cookies.permanent.signed[:user_id] = user.id
		cookies.permanent[:remember_token] = user.remember_token
	end

	# used to retrieve user on subsequent pages
	# because sessions_helper.rb is included in the main app controller,
	# it can be called in many different places like:
	# <%= current_user.name %> in a view
	# redirect_to current_user in a controller
	# refactored at 9.9
	def current_user
		if session[:user_id] #sessions are destroyed after browser closes
			@current_user ||= User.find_by(id: session[:user_id]) 
		elsif cookies.signed[:user_id]
			user = User.find_by(id: cookies.signed[:user_id])
			if user && user.authenticated?(cookies[:remember_token])
				log_in user
				@current_user = user
			end
		end
	end

	def logged_in?
		!current_user.nil?
	end

	def forget(user)
		user.forget #model method
		cookies.delete(:user_id)
		cookies.delete(:remember_token)
	end

	def log_out
		forget(current_user)
		session.delete(:user_id)
		@current_user = nil
	end
end
<file_sep>/app/models/post.rb
class Post < ApplicationRecord
    validates :title, presence: true, length: {minimum: 3, maximum: 35}
	validates :body,  presence: true, length: {minimum: 3, maximum: 500}
	validates :user_id, presence: true

	belongs_to :user
end
<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
    before_action :logged_in_user, only: [:new]

    def new
        @post = Post.new
    end
  
    def create
        @post = Post.new(post_params)
        @post.user_id = current_user.id
        if @post.save
            flash[:success] = "Post Created!"
            redirect_to @post
        else
            flash.now[:warning] = "There were errors with your post."
            render new_post_path
        end
    end
  
    def index
        @posts = Post.all
    end
  
    def show
        @post = Post.find_by(id: params[:id])
        if @post != nil
            @user = User.find_by(id: @post.user_id)
        end
    end
  
    private
        def post_params
            params.require(:post).permit(:title, :body)
        end
end
