stevekaplan123/carpe_diem

View on GitHub
app/controllers/friendships_controller.rb

Summary

Maintainability
A
1 hr
Test Coverage
class FriendshipsController < ApplicationController
  before_action :set_friendship, only: [:show, :edit, :update, :destroy]

  # GET /friendships
  # GET /friendships.json
  def index
    @friendships = Friendship.all
  end

  def add_new_friend
    friend = User.find_by(name: params[:friend_name])
 
    if not friend
      flash[:danger] = 'We can\'t find your friend in our system.'
    elsif current_user?(friend)
      flash[:danger] = 'Can\'t add yourself as friend :('
    elsif Friendship.friends?(current_user, friend)
      flash[:danger] = 'You have already added this friend.'
    else
      flash[:success] = 'You have added a new friend.'
      @friendship = Friendship.create(user_id: current_user.id, user_name: current_user.name, 
                                      friend_id: friend.id, friend_name: friend.name)
    end
    redirect_to current_user
  end

  # GET /friendships/1
  # GET /friendships/1.json
  def show
  end

  # GET /friendships/new
  def new
    @friendship = Friendship.new
  end

  # GET /friendships/1/edit
  def edit
  end

  # POST /friendships
  # POST /friendships.json
  def create
    @friendship = Friendship.new(friendship_params)

    respond_to do |format|
      if @friendship.save
        format.html { redirect_to @friendship, notice: 'Friendship was successfully created.' }
        format.json { render :show, status: :created, location: @friendship }
      else
        format.html { render :new }
        format.json { render json: @friendship.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /friendships/1
  # PATCH/PUT /friendships/1.json
  def update
    respond_to do |format|
      if @friendship.update(friendship_params)
        format.html { redirect_to @friendship, notice: 'Friendship was successfully updated.' }
        format.json { render :show, status: :ok, location: @friendship }
      else
        format.html { render :edit }
        format.json { render json: @friendship.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /friendships/1
  # DELETE /friendships/1.json
  def destroy
    @friendship.destroy
    respond_to do |format|
      format.html { redirect_to :back, notice: 'Friendship was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_friendship
      @friendship = Friendship.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def friendship_params
      params.require(:friendship).permit(:user_id, :user_name, :friend_id, :friend_name)
    end
end