Search code examples
reactjsruby-on-railsrubyruby-on-rails-4controller

How to render some specific information of the loggedinUser?


Hi I have react front end and rails backend.There is login and logout system implemented. The app is a reservation booking app.So when I make a post request to my reservations I want only reservations of logged In user to appear under My reservation tab.Currently Reservations of all the users are appearing under that sections.(As in different people logged in from different accounts everyones reservations can be seen).How can I filter only reservations of logged in user Pls check out my code . Application controller

class ApplicationController < ActionController::API
  include ActionController::Cookies
  rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response
  before_action :authorize
  
   private
   def authorize
     puts "hello",session[:user_id]
     @current_user = User.find_by(id: session[:user_id])
      render json: { errors: ["Not authorized"] }, status: :unauthorized unless @current_user
   end
 
   def render_unprocessable_entity_response(exception)
     render json: { errors: exception.record.errors.full_messages }, status: :unprocessable_entity
   end
end

Here are my routes for reference

Rails.application.routes.draw do
  
  resources :reservations,only: [:index,:create,:update,:destroy]
  resources :reviews,only: [:index,:create,:destroy]
  resources :restaurants,only: [:index]
 

  
  post "/signup", to: "users#create"
  get "/me", to: "users#show"
  post "/login", to: "sessions#create"
  delete "/logout", to: "sessions#destroy"
  
end

User controller

class UsersController < ApplicationController
  rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response
  skip_before_action :authorize, only: [:create]
   def create
      user = User.create!(user_params)
      session[:user_id] = user.id
      render json: user, status: :created
    end
    
    def show
      render json: @current_user
    end

    def index
      user=User.all 
      render json: user
    end


  private     
  def user_params
      params.permit(:name,:email,:password)

  end
  def render_unprocessable_entity_response(invalid)
    render json: { errors: invalid.record.errors.full_messages }, status: :unprocessable_entity
  end
end

Sessions controller

class SessionsController < ApplicationController
  skip_before_action :authorize, only: :create
  def create
      user = User.find_by(email: params[:email]) #verifying
      if user&.authenticate(params[:password])
        session[:user_id] = user.id
        render json: user
      else
        render json: { errors: ["Invalid username or password"] }, status: :unauthorized
      end
    end

  def destroy
      session.delete :user_id
      head :no_content
    end
  

end

Reservation controller

class ReservationsController < ApplicationController
    def index
        reservation =Reservation.all
        render json: reservation

    end

    def create
        reservation=Reservation.create!(reservation_params)
        render json: reservation,status: :created


    end

    def update
        reservation = Reservation.find_by(id: params[:id])
        review.update!(reservation_params)
        render json: reservation,status: :ok

    end
  

    def destroy
   
        reservation = @current_user.reservation.find(params[:id])
        if @current_user
        reservation.destroy
        else
            render json: {error: "Reservation of someone else."}, status: :not_found
        end
    end



    private
    
    def reservation_params
        params.permit(:name, :date, :time, :num, :contact, :occasion,:user_id,:restaurant_id)

    end
   
end

For my front end

import { useState,useEffect } from "react";
import ReservationCard from "./ReservationCard";
function MyReservations({user}){
    const[reservations,setReservations]=useState([]);
    useEffect(()=>{
        fetch("/reservations")
        .then(res=>res.json())
        .then(reservationData=>{
          setReservations(reservationData)
        })
      },[])

     
    return(
        <>
        <h1>My Reservations</h1>
        {reservations.map((reservation)=>(
        <ReservationCard key={reservation.id} reservation={reservation} />
        
       ))

       }
        </>
    )
}
export default MyReservations;

Solution

  • I guess that your User model has a line like this

    has_many :reservations
    

    and because the current user is stored in @current_user in the authorize method you should be to only show the current user's reservations by changing the ReservationsController#index method to:

    def index
      reservations = @current_user.reservations
      
      render json: reservations
    end