LoginSignup
13
12

More than 1 year has passed since last update.

Rails パンくずリスト gretel の使い方

Last updated at Posted at 2020-05-14

概要

こんにちは、今回はパンくずリストを作成する際に使ったgretelというgemの使い方を記載します。

gretel

こんな感じです。
スクリーンショット 2020-05-14 19.22.42.png

インストール

gem 'gretel'

bundle installします。

ファイル作成

下記コマンドを打つと専用の設定ファイルが作成されます。

$ rails generate gretel:install

config/breadcrumbs.rbというファイルが作成されたはずです。

パンくずを作成

前項で作成された設定ファイルにパンくずを設定していきます。

config/breadcrumbs.rb
crumb :top do
  link "トップページ", root_path
end

crumb :shops do
  link "カフェ一覧", shops_path
  parent :top
end

crumb :user do |user|
  link user.username, user_path(user)
  parent :shops
end

crumb :edit_user do |user|
  link "編集", edit_user_registration_path
  parent :user, user
end

crumb :following_user do |user|
  link "フォロー", following_user_path
  parent :user, user
end

crumb :followers_user do |user|
  link "フォロワー", followers_user_path
  parent :user, user
end

crumb :shop do |shop|
  link shop.name, shop_path
  parent :shops
end

crumb :edit_shop do |shop|
  link "編集", edit_shop_path
  parent :shop, shop
end

今回は最大4階層までのパンくずを設定しました。

crumbでパンくずを定義し、linkにパスを記述します。
parentには親となるパンくずを設定。

parent :モデル名 と記述したあとに注目してください。

crumb :edit_shop do |shop|
  link "編集", edit_shop_path
  parent :shop, shop #ここに注目!
end

このカンマ以降の記述が無ければ対象のビューで
NoMethodErrorが出てしまいます。

この書き方がなかなか分かりませんでした。

viewに配置

view側はシンプルです。

html.erb
<% breadcrumb :user, @user %>
<%= breadcrumbs separator: " &rsaquo; " %>

これだけです。

separatorでパンくずの階層である > を追加しています。
その他にも色々とオプションがあるのでぜひ公式で確認してみてください。

以上です。
お付き合い頂きありがとうございました。

13
12
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
13
12