1
4

More than 3 years have passed since last update.

【Rails】投稿カテゴリ機能(メモ)

Last updated at Posted at 2021-09-01

目標

  • カテゴリ機能の実装

環境

  • Rails: 6.1.3
  • ruby: 3.0.0
  • mac: OS

前提

  • 簡易的なTodoApp
  • 投稿機能実装済

実装

categoryモデル作成

ターミナル
$ rails g model Category name:string

マイグレーションファイル生成。

class CreateCategories < ActiveRecord::Migration[6.1]
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps
    end
  end
end
$ rails db:migrate

postテーブルにカテゴリカラムを追加

ターミナル
$ rails g migration AddCategoryIdToPosts category_id: integer

マイグレーションファイル生成。

class AddCategoryIdToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :category_id, :integer
  end
end
ターミナル
$ rails db:migrate

モデルの関連付け(アソシエーション)

postは複数のカテゴリを持てるのでhas_many :categories

app/models/post.rb
class Post < ApplicationRecord
  has_many :categories

カテゴリは1つの投稿に属しているのでbelongs_to :post

app/models/category.rb
class Category < ApplicationRecord
   belongs_to :post

ルーティング記述

config.routes.rb
Rails.application.routes.draw do
   resources :categories
end

categoryコントローラ作成

ターミナル
$ rails g controller categories 

生成されたコントローラに記述。

app/controllers/categories_controller.rb
class CategoriesController < ApplicationController

  def index
    @categories = Category.all
  end

  def create
    @category = Category.new(category_params)
    @category.save
  end
end

private

def category_params
  params.require(:category).permit(:name)
end
app/controllers/posts_controller.rb
private

def post_params
  params.require(:post).permit(:content, :title, :category_id)
end

ビュー記述

カテゴリを追加できるフォーム。

app/views/categories/new.html.erb
<h2>カテゴリの追加 </h2>
 <%= form_with model: @category, local: true do |f| %>
    <div class='from_input'>
      <%= f.label :name %>
      <%= f.text_field :name %>
    </div>
    <div class="form_action">
      <%= f.submit "登録する", class: "btn btn-primary" %>
    </div>
 <% end %>


スクリーンショット 2021-08-31 1.22.16.png

追加したカテゴリを確認できます。

app/views/categories/index.html.erb
<h1>カテゴリ一覧</h1>
  <table class="table table-hover">
    <tbody>
      <% @categories.each do |cate| %>
        <tr>
          <td><%= link_to cate.name, posts_path(category_id: cate.id) %></td>
          <td><%= cate.created_at.to_s(:datetime_jp) %>作成</td>
        </tr>
      <% end %>
    </tbody>
  </table>

スクリーンショット 2021-08-31 1.52.40.png

新しい投稿をする際にカテゴリを選択できるようにフォームに追記。

app/views/posts/new.html.erb

    <h2>投稿ページ</h2>

    <%= form_with model: @post do |f| %>
        <div class="form-input">
            <%= f.label :title, 'タイトル' %>
            <%= f.text_field :title, class: "form-control" %>
        </div>
        <div class="form_input">
            <%= f.label :content, '本文' %>
            <%= f.text_field :content, class: "form-control" %>
        </div>

        <div class="form_input">
            <%= f.label :category_id %>

            <%= f.collection_select :category_id, Category.all, :id, :name, { prompt: '選択してください' }, class: 'form-control' %>
        </div>
        <div class="form_action row">
            <%= f.submit "投稿する", class: "btn btn-primary"%>
        </div>
    <% end %>

スクリーンショット 2021-08-31 2.06.21.png

これでカテゴリが選択できます。

まとめ

今後も使う可能性のある機能だと思うので備忘録として残しておきます。

1
4
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
4