🦓

[Rails]スコープ実装メモ

2023/08/11に公開

はじめに

スコープのMVCの実装メモになります。

環境

Rails 7.0.4.3
ruby 3.2.1

モデル

モデル内にてスコープを作成します。

app/models/post.rb
class Post < ApplicationRecord
# bad
  scope :individual, -> { where(dev_type: 0) }
  scope :team, -> { where(dev_type: 1) }
  
# good
  scope :by_dev_type, ->(dev_type) { where(dev_type: dev_type) }
  scope :by_phase, ->(phase) { where(phase: phase) }
end

ルーティング

config/routes.rb
Rails.application.routes.draw do
  resources :projects do
    collection do
      get 'type/:dev_type', action: :by_dev_type, as: :by_dev_type
      get 'phase/:phase', action: :by_phase, as: :by_phase
    end
  end
end

コントローラー

index.html.erbのビューを使いますが、タイトルだけを動的に出力させます。

app/controllers/posts_controller.rb
class ProjectsController < ApplicationController
...
    def by_dev_type
        @dev_type = params[:dev_type]
        @title = I18n.t("enums.project.dev_type.#{@dev_type}")
        @projects = Project.by_dev_type(@dev_type)
        render :index
    end

    def by_phase
        @phase = params[:phase]
        @title = I18n.t("enums.project.phase.#{@phase}")
        @projects = Project.by_phase(@phase)
        render :index
    end
end

ビュー

一覧ページにタイトの表示を切り替えられるようにます。

app/views/posts/index.html.erb
<% if @title.present? %>
    <h2><%= @title %></h2>
<% else %>
    <h2>他のタイトル</h2>
<% end %>

終わりに

一覧ページにさらにスコープの絞り込み一覧を表示させたかったので以上のように実装してみました。

Discussion