1.概要
本記事では、Ruby on Rails を使って実装した投稿アプリにおいて、投稿に対してカテゴリ(Category)をプルダウン形式で1つだけ選択できる機能を追加する方法を解説します。
投稿時にカテゴリを選べるだけでなく、一覧ページでカテゴリごとの絞り込み表示や、詳細ページでカテゴリ名の表示も可能になります。
🎯 完成イメージ
- 投稿(Article)にカテゴリ(Category)を1つだけ選べる
- 投稿一覧をカテゴリで絞り込める
- 投稿詳細ページにカテゴリ名を表示できる
2.モデルの作成
| モデル | 用途 |
|---|---|
Category |
投稿のカテゴリ(ジャンル)を管理する |
Tweet |
投稿の本文・タイトルなどの内容を管理する |
コマンドプロンプト
rails g model Category name:string
rails g migration AddCategoryToTweets category:references
rails db:migrate
📝 カラムやモデル名は自由に変更してOK!
3.モデルの関連付け(アソシエーション)
models/category.rb
class Category < ApplicationRecord
has_many :tweets, dependent: :destroy # 追加
end
models/tweet.rb
class Tweet < ApplicationRecord
belongs_to :category # 追加
end
4.投稿フォームにカテゴリのプルダウンを追加
views/tweets/new.html.erb
<h3>新規投稿</h3>
<%= form_for @tweet do |f| %>
# ここから
<div class="form-group">
<%= f.label :カテゴリ %>
<%= f.collection_select :category_id, Category.all, :id, :name, include_blank: "カテゴリを選択してください" %>
</div>
# ここまで
<% end %>
5.コントローラーの修正(tweets_controller.rb)
controllers/tweets_controller
# ここから
def index
if params[:category_id].present?
@tweets = Tweet.where(category_id: params[:category_id])
else
@tweets = Tweet.all
end
end
#ここまで
def tweet_params
params.require(:tweet).permit(:title, :body, :category_id) # category_idを追加
end
6.一覧ページでカテゴリ絞り込みプルダウン
views/tweets/index.html.erb
# ここから
<%= form_tag tweets_path, method: :get do %>
<%= select_tag :category_id,
options_from_collection_for_select(Category.all, :id, :name, params[:category_id]),
prompt: "カテゴリで絞る",
onchange: "this.form.submit();" %>
<% end %>
# ここまで
# 以下省略
7.詳細ページでカテゴリ表示
views/tweets/show.html.erb
<p>カテゴリ: <%= @tweet.category.name if @tweet.category.present? %></p> # 追加
8.seedデータ(カテゴリ)
db/seeds.rb
Category.destroy_all
Category.create([
{ name: '趣味' },
{ name: '学習' },
{ name: '日常' },
{ name: '仕事' },
{ name: 'その他' }
])
コマンドプロンプト
rails db:seed