1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】パンくず機能について

Posted at

記事概要

Ruby on Railsにパンくず機能(リンクを設置したリストを画面に表示させる機能)を実装する方法について、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している

サンプルアプリ(GitHub)

gretel(Gem)

リンクを設置したリストを画面に表示する機能を実装できるGem

パンくずの親子関係を設定するファイル

confing/breadcrumbs.rb
crumb "現在のページ名(表示させるビューにもページ名記述)" do
  link "パンくずリストでの表示名", "アクセスしたいページのパス"
  parent :親要素のページ名前のページ
end

手順

  1. gretel(Gem)を導入する
    詳細は、こちらを参照
  2. パンくずのリストを表示する、ビューを作成する
    1. app/views/users/index.html.erb
      <h1>Users#index</h1>
      <p><%= link_to "ツイートへ", tweets_index_path %></p>
      
    2. app/views/tweets/index.html.erb
      <h1>Tweets#index</h1>
      <p><%= link_to "コンタクトへ", contacts_index_path %></p>
      
    3. app/views/contacts/index.html.erb
      <h1>Contacts#index</h1>
      <p>Find me in app/views/contacts/index.html.erb</p>
      
  3. ブラウザにて、下記のように表示されていることを確認する
    Image from Gyazo
  4. ターミナルで下記コマンドを実行し、パンくずの親子関係を設定するファイルを作成する
    % rails g gretel:install
    
  5. config/breadcrumbs.rbが作成される
  6. パンくずの親子関係を設定するファイルを編集する
    config/breadcrumbs.rb
    crumb :root do
      link "Home", root_path
    end
    
    crumb :tweets do
      link "ツイート一覧", tweets_index_path
      parent :root
    end
    
    crumb :contacts do
      link "コンタクト", contacts_index_path
      parent :tweets
    end
    
  7. breadcrumbs.rbファイルで実装したパンくずを画面に表示するため、views/layouts/application.html.erbを編集する
      <!-- 省略 -->
      <body>
        <!-- パンくずを画面に表示する -->
        <%= breadcrumbs separator: " &rsaquo; " %>
    
        <%= yield %>
      </body>
    </html>
    
    separator: " &rsaquo;”は、パンくず間の区切りである「>」を示す
  8. indexファイルの編集を行う
    1. app/views/users/index.html.erb
      <h1>Users#index</h1>
      <p><%= link_to "ツイートへ", tweets_index_path %></p>
      <% breadcrumb :root %>
      
    2. app/views/tweets/index.html.erb
      <h1>Tweets#index</h1>
      <p><%= link_to "コンタクトへ", contacts_index_path %></p>
      <% breadcrumb :tweets %>
      
    3. app/views/contacts/index.html.erb
      <h1>Contacts#index</h1>
      <p>Find me in app/views/contacts/index.html.erb</p>
      <% breadcrumb :contacts %>
      
  9. ブラウザで確認する
    Image from Gyazo
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?