LoginSignup
2
1

More than 3 years have passed since last update.

[Rails]パンくず機能

Last updated at Posted at 2020-11-19

はじめに

画面遷移をわかりやすくするために、gretelというgemを使用してパンくず機能を実装しました。
パンくずリスト

目次

  • 1. gretelのインストール
  • 2. パンくずの設定
  • 3. ビュー

1. gretelのインストール

gretelというgemを用いることで、リンクを設置したリストを画面に表示させるパンくずを実装することができます。

gemfile
gem "gretel"
ターミナル
bundle install

2. パンくずの設定

パンくずの親子関係を設定するファイルを作成します。

ターミナル
rails g gretel:install
config/breadcrumbs.rb
crumb "現在のページ名(表示させるビューにもページ名記述)" do
  link "パンくずリストでの表示名", "アクセスしたいページのパス"
  parent :親要素のページ名(前のページ)
end
config/breadcrumbs.rb
crumb :root do
  link "ホーム", root_path
end
crumb :posts do
  link "クチコミ一覧", posts_path
  parent :root
end

crumb :post_show do |post|
  link post.name, post_path(post)
  parent :posts
end

crumb :user do |user| 
  link user.nickname, user_path(user)
  parent :root
end

# 親カテゴリーのパンくず
crumb :parent_category do |category|
  category = Category.find(params[:id]).root
  link "#{category.name}", search_post_path(category)
  parent :root
end

# 子カテゴリーのパンくず
crumb :child_category do |category|
  category = Category.find(params[:id])
  # 表示しているページが子カテゴリーの一覧ページの場合
  if category.has_children?
    link "#{category.name}", search_post_path(category)
    parent :parent_category

  # 表示しているページが孫カテゴリーの一覧ページの場合
  else
    link "#{category.parent.name}", search_post_path(category.parent)
    parent :parent_category
  end
end

# 孫カテゴリーのパンくず
crumb :grandchild_category do |category|
  category = Category.find(params[:id])
  link "#{category.name}", search_post_path(category)
  parent :child_category
end

crumb :post_new do
  link "新しいクチコミ投稿", new_post_path
  parent :root
end

crumb :name_search do |search|
  if search == ""
    link "クチコミ検索結果", name_search_posts_path
  else
    link "「#{search}」のクチコミ検索結果", name_search_posts_path
  end
  parent :posts
end

カテゴリーのパンくずリストは、親カテゴリー > 子カテゴリー > 孫カテゴリーになるように設定しています。
子カテゴリーの処理については、孫カテゴリーのページから呼び出した場合(孫カテゴリーを選択した時)と、子カテゴリーのページから呼び出した場合(子カテゴリーを選択した時)の2つの条件で処理を変えるようにします。

3. ビュー

今回はパンくずを表示させたいところだけに適応したかったので、部分テンプレートを作成しました。

app/views/shared/_breadcrumbs.html.erb
<div>
  <%= breadcrumbs separator: " &rsaquo; " %>
</div>

separator: " &rsaquo; “はパンくずの区切りである「>」を示します。

投稿一覧のindexファイルだけ載せておきます。

app/views/posts/index.html.erb
~~
<% breadcrumb :posts %>
<%= render "shared/breadcrumbs" %>
~略~

breadcrumb :postsはbreadcrumbs.rbで設定したページ名を記述しています。

参考リンク

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1