学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails7.1 | 仕事売買アプリ作成 | 34 | Action

↓↓クリックして頂けると励みになります。



33 | Offer】 << 【ホーム】 >> 【35 | 仕事とリクエスト




登録したリクエストの申し込みに対し、クライアントが仕事を依頼したり、断ったりできるアクションボタンを実装していきます。
その際、ステータスも変更し、表示できるようにします。

コントローラー



「app\controllers\requests_controller.rb」ファイルに以下の記述を追加します。


1.記述追加 app\controllers\requests_controller.rb(4,5行目)
3行目の最後に「, :my_offers」の記述を追加します。
4行目の最後に「, :offers」の記述を追加しています。

  before_action :set_request, except: [:new, :create, :index, :list, :my_offers]
  before_action :is_authorised, only: [:edit, :update, :destroy, :offers]



2.記述追加 app\controllers\requests_controller.rb(57行目)

  def my_offers
    @offers = current_user.offers
  end



app\controllers\requests_controller.rb

class RequestsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_request, except: [:new, :create, :index, :list, :my_offers]
  before_action :is_authorised, only: [:edit, :update, :destroy, :offers]
  before_action :set_categories, only: [:new, :edit, :list]
 

  def index
    @requests = current_user.requests
  end

  def new
    @request = current_user.requests.build
  end

  def create
    @request = current_user.requests.build(request_params)
    if @request.save
      redirect_to requests_path, notice: "保存しました"
    else
      redirect_to request.referrer, flash: {error: @request.errors.full_messages.join(', ')}
    end
  end

  def edit
  end

  def update
    if @request.update(request_params)
      redirect_to requests_path, notice: "保存しました"
    else
      redirect_to request.referrer, flash: {error: @request.errors.full_messages.join(', ')}
    end
  end

  def show
  end

  def destroy
    @request.destroy
    redirect_to requests_path, notice: "削除しました"
  end

  def list
    @category_id = params[:category]

    if @category_id.present?
      @requests = Request.where(category_id: @category_id)
    else
      @requests = Request.all
    end
  end

  def offers
    @offers = @request.offers
  end

  def my_offers
    @offers = current_user.offers
  end

  private
  def set_categories
    @categories = Category.all
  end

  def set_request
    @request = Request.find(params[:id])
  end

  def is_authorised
    redirect_to root_path, alert: "あなたに権限はありません。" unless current_user.id == @request.user_id
  end

  def request_params
    params.require(:request).permit(:description, :category_id, :delivery, :budget, :attachment_file, :title)
  end
end



「app\controllers\offers_controller.rb」ファイルの記述を以下のように変更します。


記述変更 app\controllers\offers_controller.rb
1. 18行目の記述を以下の記述に変更します。

redirect_to my_offers_path, notice: "保存しました"



2.申し込みに対するアクションを実装します。(27行目)

    def accept
        if @offer.pending?
            @offer.accepted!
                flash[:notice] = "お仕事をお願いしました"
        end
        redirect_to request.referrer
    end

    def reject
        if @offer.pending?
            @offer.rejected!
            flash[:notice] = "お断りしました"
        end
        redirect_to request.referrer
    end



app\controllers\offers_controller.rb

class OffersController < ApplicationController
    before_action :authenticate_user!
    before_action :set_offer, only: [:accept, :reject]
    before_action :is_authorised, only: [:accept, :reject]

    def create
        req = Request.find(offer_params[:request_id])

        if req && req.user_id == current_user.id
            redirect_to request.referrer, alert: "自分のリクエストに申し込みはできません。"
        
        elsif Offer.exists?(user_id: current_user.id, request_id: offer_params[:request_id])
            redirect_to request.referrer, alert: "申し込みできるのは1回だけです"
        
        else
            @offer = current_user.offers.build(offer_params)
            if @offer.save
                #redirect_to request.referrer, notice: "保存しました"
                redirect_to my_offers_path, notice: "保存しました"
                
            else
                redirect_to request.referrer, flash: {error: @offer.errors.full_messages.join(', ')}
            end
        end
    end

    def accept
        if @offer.pending?
            @offer.accepted!
                flash[:notice] = "お仕事をお願いしました"
        end
        redirect_to request.referrer
    end

    def reject
        if @offer.pending?
            @offer.rejected!
            flash[:notice] = "お断りしました"
        end
        redirect_to request.referrer
    end

    private

    def set_offer
        @offer = Offer.find(params[:id])
    end

    def is_authorised
        redirect_to root_path, alert: "権限がありません。" unless current_user.id == @offer.request.user_id
    end

    def offer_params
        params.require(:offer).permit(:amount, :days, :note, :request_id, :status)
    end
end


ルート設定



ルートの設定をします。


記述追加 config\routes.rb
1.14行目に「get '/my_offers', to: 'requests#my_offers'」の記述を追加しています。


2.22,23行目に以下の記述を追加しています。

  put '/offers/:id/accept', to: 'offers#accept', as: 'accept_offer'
  put '/offers/:id/reject', to: 'offers#reject', as: 'reject_offer'


Rails.application.routes.draw do

  # ルートを app\views\pages\home.html.erb に設定
  root 'pages#home'

  # get
  get 'pages/home'
  get '/dashboard', to: 'users#dashboard'
  get '/users/:id', to: 'users#show', as: 'user'
  get '/selling_orders', to: 'orders#selling_orders'
  get '/buying_orders', to: 'orders#buying_orders'
  get '/all_requests', to: 'requests#list'
  get '/request_offers/:id', to: 'requests#offers', as: 'request_offers'
  get '/my_offers', to: 'requests#my_offers'

  # post
  post '/users/edit', to: 'users#update'
  post '/offers', to: 'offers#create'

  # put
  put '/orders/:id/complete', to: 'orders#complete', as: 'complete_order'
  put '/offers/:id/accept', to: 'offers#accept', as: 'accept_offer'
  put '/offers/:id/reject', to: 'offers#reject', as: 'reject_offer'

  resources :gigs do
    member do
      delete :delete_photo
      post :upload_photo
    end
    resources :orders, only: [:create]
  end

  resources :requests
  
  # device
  devise_for :users, 
    path: '', 
    path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'},
    controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
  # Can be used by load balancers and uptime monitors to verify that the app is live.
  get "up" => "rails/health#show", as: :rails_health_check

  # Defines the root path route ("/")
  # root "posts#index"
end


ビュー



フリーランサー(仕事をする人)がクライアントのリクエストに申し込んだオファーを確認するビューを作成します。
「app\views\requests」フォルダに「my_offers.html.erb」ファイルを新規作成して下さい。


app\views\requests\my_offers.html.erb(新規作成したファイル)

<div class="container mt-4">
    <div class="card">
        <div class="card-body">
            <h5 class="card-title text-danger h3 font1">申し込んだオファー一覧(フリーランサー)</h5>

            <% if @offers.blank? %>
                <h5 class="font1">表示できるオファーはありません。</h5>
            <% end %>            

            <% @offers.each do |o| %>
                <div class="card mt-4">
                    <div class="card-body">
                        <div class="mt-2">
                            <span class="alert alert-<%= 'warning' if o.pending? %><%= 'success' if o.accepted? %><%= 'danger' if o.rejected? %>">
                                <% if o.pending? %>
                                    進行中
                                <% elsif o.accepted? %>
                                    オファー成功
                                <% else %>
                                    お断り
                                <% end %>
                            </span>
                        </div>
     
                        <ul class="list-group mt-4">

                            <li class="list-group-item" style="border: none;">
                                <span class="font1">オファー日:</span><%= I18n.l(o.created_at, format: :full_date) %>
                            </li>
                            <li class="list-group-item" style="border: none;">
                                <span class="font1">リクエスト名:</span>
                                <%= link_to o.request.title, request_path(o.request), class: "btn btn-light" %>
                            </li>
                            <li class="list-group-item" style="border: none;">
                                <span class="font1">期日:</span> <%= o.days %></li>
                            <li class="list-group-item" style="border: none;">
                                <span class="font1">リクエスト予算:</span><%= number_to_currency(o.request.budget) %>
                            </li>                                 
                            <li class="list-group-item" style="border: none;">
                                <span class="font1">オファー価格:</span><%= number_to_currency(o.amount) %>
                            </li>                  
                        </ul>

                    </div>
                </div>
            <% end %>
        </div>
    </div>
</div>



ブラウザを確認します。
ブラウザ確認
http://localhost:3000/my_offers

PCレイアウト
PCレイアウト


モバイルレイアウト
モバイルレイアウト



リクエストをしたクライアントが申し込みに対して仕事を依頼したり、断ったりできるボタンを追加します。
「app\views\requests\offers.html.erb」ファイルに以下の記述を追加します。


記述更新 app\views\requests\offers.html.erb(47行目)
7行目に以下の記述を追加します。

<% if o.pending? %>
    <div>
        <%= link_to accept_offer_path(o), data: { turbo_method: :put, turbo_confirm: "お仕事をお願いしてよろしいですか?" }, class: "btn btn-outline-success" do %>
            <i class="far fa-check-circle fa-lg"></i>お仕事をお願いする
        <% end %>
        
        <%= link_to reject_offer_path(o), data: { turbo_method: :put, turbo_confirm: "お仕事をお断りしてよろしいですか?" }, class: "btn btn-outline-danger" do %>
            <i class="far fa-times-circle fa-lg"></i>お断りする
        <% end %>
    </div>
<% else %>
    <span class="alert alert-<%= 'success' if o.accepted? %><%= 'danger' if o.rejected? %>">
        <% if o.accepted? %>
            仕事をお願いしました
        <% else %>
            断りました
        <% end %>
    </span>
    <br/>
    <br/>
<% end %>



app\views\requests\offers.html.erb

<div class="container">
    <div class="card mb-2 mt-2">
        <div class="card-body">
            <% @offers.each do |o| %>
                <ul class="list-group mt-4">
                    <li class="list-group-item" style="border: none;">

                        <% if o.pending? %>
                            <div>
                                <%= link_to accept_offer_path(o), data: { turbo_method: :put, turbo_confirm: "お仕事をお願いしてよろしいですか?" }, class: "btn btn-outline-success" do %>
                                    <i class="far fa-check-circle fa-lg"></i>お仕事をお願いする
                                <% end %>
                                
                                <%= link_to reject_offer_path(o), data: { turbo_method: :put, turbo_confirm: "お仕事をお断りしてよろしいですか?" }, class: "btn btn-outline-danger" do %>
                                    <i class="far fa-times-circle fa-lg"></i>お断りする
                                <% end %>
                            </div>
                        <% else %>
                            <span class="alert alert-<%= 'success' if o.accepted? %><%= 'danger' if o.rejected? %>">
                                <% if o.accepted? %>
                                    仕事をお願いしました
                                <% else %>
                                    断りました
                                <% end %>
                            </span>
                            <br/>
                            <br/>
                        <% end %>

                        <span class="font1">リクエスト名:</span>
                        <%= o.request.title %>
                    </li>
                    <li class="list-group-item" style="border: none;">
                        <span class="font1">申し込み日:</span><%= I18n.l(o.created_at, format: :full_date) %>
                    </li>
                    <li class="list-group-item" style="border: none;">
                        <span class="font1">フリーランサー</span>                            
                        <%= link_to user_path(o.user), style: "text-decoration:none;" do %>
                            <%= image_tag avatar_url(o.user), class: "bd-placeholder-img figure-img img-fluid rounded-pill", style: "width: 50px;" %>
                            <span class="font2 text-dark h4"><%= o.user.full_name %></span>
                        <% end %>            
                    </li>   
                    <li class="list-group-item" style="border: none;">
                        <span class="font1">コメント:</span> <%= o.note %>        
                    </li>                         
                    <li class="list-group-item" style="border: none;">
                        <span class="font1">期日:</span> <%= o.days %></li>
                    <li class="list-group-item" style="border: none;">
                        <span class="font1">価格:</span><%= number_to_currency(o.amount) %>
                    </li>                                            
                </ul>
            <% end %>
        </div>
    </div>
</div>



アクションボタンが機能するようになりました。
リクエストを出したクライアント側で確認してください。
ブラウザ確認
http://localhost:3000/request_offers/5

リクエスト一覧
リクエスト一覧



オファーを受けてみます。

クライアントがオファーを受ける
クライアントがオファーを受ける



フリーランサー側でステータスを確認してみます。
http://localhost:3000/my_offers

フリーランサー ステータス確認
フリーランサー ステータス確認



ナビゲーションバーにリンクを追加します。


記述追加 app\views\shared\_navbar.html.erb
39行目に以下の記述を追加しています。

<li><%= link_to  "申し込み確認", my_offers_path, class: "dropdown-item btn btn-light" %></li>


<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="/"><span class="font1">Gig Hub7</span></a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <!-- もしログインしていなかったら-->
        <% if (!user_signed_in?) %>
        <li class="nav-item" style="margin-bottom: 0.1rem;">
          <span style="margin-left: 1rem;">
          <%= link_to  "新規登録", new_user_registration_path, class: "btn btn-danger" %>
          </span>
        </li>
        <li class="nav-item">
          <span style="margin-left: 1rem;">
            <%= link_to  "ログイン", new_user_session_path, class: "btn btn-success text-light" %>
          </span>
        </li>
      </ul>
      <!-- ログインしていたら -->
      <% else %>
      <ul class="navbar-nav" style="margin-left: 2rem;">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">

          <figure style="position:relative; top: 0.2rem;" class="avatar <%= current_user.status ? "online" : "offline" %>"></figure>  
          <%= image_tag avatar_url(current_user), class: "bd-placeholder-img figure-img img-fluid rounded-pill", style: "width: 40px; height: 30px;" %>          
            <%= current_user.full_name %>
          </a>
          <ul class="dropdown-menu">
          <li><%= link_to  "ダッシュボード", dashboard_path, class: "dropdown-item btn btn-lightt" %></li>
          <li><%= link_to  "ユーザ登録情報編集", edit_user_registration_path, class: "dropdown-item btn btn-light" %></li>
          <li><%= link_to  "リクエスト", all_requests_path, class: "dropdown-item btn btn-light" %></li>
          <li><hr class="dropdown-divider"><span class="badge bg-danger" style="margin-left: 1rem;">フリーランサー</span></li>
          <li><%= link_to  "仕事を新規登録", new_gig_path, class: "dropdown-item btn btn-light" %></li>
          <li><%= link_to  "仕事確認", selling_orders_path, class: "dropdown-item btn btn-light" %></li>
          <li><%= link_to  "申し込み確認", my_offers_path, class: "dropdown-item btn btn-light" %></li>
          <li><hr class="dropdown-divider"><span class="badge bg-primary" style="margin-left: 1rem;">クライアント</span></li>
          <li><%= link_to  "依頼確認", buying_orders_path, class: "dropdown-item btn btn-light" %></li>
          <li><%= link_to  "リクエスト登録", new_request_path, class: "dropdown-item btn btn-light" %></li>
          <li><%= link_to  "リクエスト確認", requests_path, class: "dropdown-item btn btn-light" %></li>
          <li><hr class="dropdown-divider"></li>
            <li><%= button_to  "ログアウト", destroy_user_session_path, method: :delete, class: "dropdown-item btn btn-light" %></li>
          </ul>
        </li>
      </ul>
      <% end %>

    </div>
  </div>
</nav>



ブラウザ確認

ナビゲーションバー更新
ナビゲーションバー更新



33 | Offer】 << 【ホーム】 >> 【35 | 仕事とリクエスト





↓↓クリックして頂けると励みになります。