0
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?

タグ機能をハッシュタグみたいに

Last updated at Posted at 2026-01-08

ゴール

GeekSalonの教材「7-9. タグ機能をつけてみよう」の補助教材としてindexページの投稿一覧に対応するタグを表示し、そのタグをクリックすることでタグのついた投稿一覧に飛べるようにします。

開発環境

Controller
tweetsController
Model
TweetModel,Tweet_tag_relationsModel,TagsModel
テーブル
tweetsテーブル,tweet_tag_relationsテーブル,tagsテーブル
GeekSalonの教材7-9を最後まで完了していることを前提にしています。

事前準備

tweetsのviewにsearch.html.erbを作成してください。
タグをクリックするとこのページに飛ぶようにします。

実装

事前準備のところで作ってもらったsearchページに飛ぶためのurlを作成します。

app/config/routes.rb
Rails.application.routes.draw do
#省略

#追加
  resources :tags do
    get 'tweets', to: 'tweets#search'
  end
#ここまで

end

tweetsコントローラーに以下のコードを記入してください。

app/model/tweets_controller
class TweetsController < ApplicationController
#省略

#追加
 def search
    @tag_list = Tag.all               # こっちの投稿一覧表示ページでも全てのタグを表示するために、タグを全取得
    @tag = Tag.find(params[:tag_id])  # クリックしたタグを取得
    @itirans = @tag.tweets.all        # クリックしたタグに紐付けられた投稿を全て表示
  end
#ここまで
end

search.html.erbに以下のコードを記入してください。

app/views/tweets/search.html.erb
<%= "#{@tag.name}一覧" %>              #クリックしてもらったタグの名前を一番上に表示しています。
<br>
<% @itirans.each do |t| %>
    <%= link_to t.body, t %>               #index.html.erbみたいに持ってきた情報をtに代入してtweetsテーブルのbodyカラムを表示します。
    <br>
    <% t.tags.each do |tag| %>
    <%= link_to tag.name, tag_tweets_path(tag_id: tag.id) %>
    <% end %>
<% end %>
end

基本的にsearchページにはindex.html.erbからコピペして持ってくれば大丈夫です!!

index.html.erbに投稿のタグを表示して、そこにsearchページに飛ぶためのurlを紐づけます。

app/views/tweets/index.html.erb
<% @tweets.each do |t| %>
たぶんこんな感じでテーブルから持ってきてもらった情報をtに代入していると思うのでここから<% end %>までの間に以下のコードを挿入してください

#追加
    <% t.tags.each do |tag| %>
        <%= link_to tag.name, tag_tweets_path(tag_id: tag.id) %>
    <% end %>
#ここまで
<% end %>

0
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
0
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?