DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on

Belay Board App Part 3: View, Accept, and Reject requests

Add a page where the current user can view all the requests made to their events (availabilities)

Nest the requests under availabilities

# config/routes.rb

resources :availabilities do
  resources :requests, only: [:index]
  # Create a URL structure like /availabilities/:availability_id/requests.
end
Enter fullscreen mode Exit fullscreen mode

Modify the RequestsController to load the requests associated with the availabilities created by the current user

# app/controllers/requests_controller.rb

class RequestsController < ApplicationController
  def index
    @user = current_user
    @requests = Request.joins(:availability).where(availabilities: { user_id: @user.id })
  end
end
Enter fullscreen mode Exit fullscreen mode

Allow user to accept or reject request

resources :availabilities do
    resources :requests, only: [:index] do
      member do
        post 'accept'
        post 'reject'
      end
    end
  end
Enter fullscreen mode Exit fullscreen mode
# app/controllers/requests_controller.rb
class RequestsController < ApplicationController
  # ...

  def accept
    @request = Request.find(params[:id])
    @request.accepted!
    redirect_to availability_requests_path(@request.availability), notice: 'Request accepted.'
  end

  def reject
    @request = Request.find(params[:id])
    @request.rejected!
    redirect_to availability_requests_path(@request.availability), notice: 'Request rejected.'
  end

  # ...
end
Enter fullscreen mode Exit fullscreen mode

Show Requests with availability information and action button

<!-- app/views/requests/index.html.erb -->
<h1>Requests on Availabilities</h1>
<table>
  <thead>
    <tr>
      <th>Availability ID</th>
      <th>Status</th>
      <th>Requester</th>
      <th>Location</th>
      <th>Description</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <% @requests.each do |request| %>
      <tr>
        <td><%= request.availability.id %></td>
        <td><%= request.status %></td>
        <td><%= request.sender.username %></td>
        <td><%= request.availability.location %></td>
        <td><%= request.availability.description %></td>
        <td>
          <%= form_with(model: request, url: accept_availability_request_path(request.availability, request), method: :post, local: true) do |form| %>
            <%= form.submit 'Accept' %>
          <% end %>
          <%= form_with(model: request, url: reject_availability_request_path(request.availability, request), method: :post, local: true) do |form| %>
            <%= form.submit 'Reject' %>
          <% end %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Next Steps

Now a user can view and act on requests made on their availabilities. Next, I will display the availabilities index as a calendar.

Top comments (0)