[RUBY] [Rails] Implementation of category function

Target

ezgif.com-video-to-gif.gif

Development environment

・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina

Premise

The following has been implemented.

Slim introductionIntroduction of Bootstrap3Implementation of posting function

Implementation

1. Model

** ① Create a category model table **

Terminal


$ rails g model Category name:string

Terminal


$ rails db:migrate

schema.rb


create_table "categories", force: :cascade do |t|
  t.string "name"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

** ② Add a column to the books table **

Terminal


$ rails g migration AddCategoryIdToBooks category_id:integer

Terminal


$ rails db:migrate

schema.rb


  create_table "books", force: :cascade do |t|
    t.integer "user_id"
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
  end

** ③ Edit each model **

book.rb


#Postscript
has_many :categories, dependent: :destroy

dependent: :destroy ➡︎ When the corresponding category is deleted, the linked book is also deleted.

category.rb


#Postscript
belongs_to :book

2. Controller

** ① Create and edit categories_controller.rb **

Create index and edit views in advance.

Terminal


$ rails g controller categories index edit

categories_controller.rb


class CategoriesController < ApplicationController
  before_action :set_category, only: [:edit, :update, :destroy]

  def index
    @category = Category.new
    @categories = Category.all
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      redirect_to categories_path
    else
      @categories = Category.all
      render 'index'
    end
  end

  def edit
  end

  def update
    if @category.update(category_params)
      redirect_to categories_path
    else
      render 'edit'
    end
  end

  def destroy
    @category.destroy
    redirect_to categories_path
  end

  private

    def set_category
      @category = Category.find(params[:id])
    end

    def category_params
      params.require(:category).permit(:name)
    end
end

** ② Add category_id to the strong parameter of books_controller.rb **

books_controller.rb


def book_params
  params.require(:book).permit(:title, :body, :category_id)
end

3. Routing

routes.rb


#Postscript
resources :categories, except: [:new, :show]

except: [:new, :show] ➡︎ Add actions other than new and show to the routing.

4. View

slim:categories/index.html.slim


.row

  .col-xs-3
    = form_with model: @category, local: true do |f|

      = f.label :name, 'Category name'
      br
      = f.text_field :name, class:'form-control'
      br

      = f.submit 'add to', class: 'btn btn-primary btn-block'

  .col-xs-9
    table.table
      thead
        tr
          th
            |Category name
          th
          th

      tbody
        - @categories.each do |category|
          tr
            td
              = category.name
            td
              = link_to 'Edit', edit_category_path(category), class: 'btn-sm btn-primary'
            td
              = link_to 'Delete', category_path(category), method: :delete, data: { confirm: '本当にDeleteしますか?' }, class: 'btn-sm btn-danger'

slim:categories/edit.html.slim


.row
  .col-xs-3

  .col-xs-6
    = form_with model: @category, local: true do |f|

      = f.label :name, 'Category name'
      br
      = f.text_field :name, class:'form-control'
      br

      = f.submit 'Save', class: 'btn btn-primary btn-block'

  .col-xs-3

slim:books/index.html.slim


.row
  .col-xs-3
    = form_with model: @book, local: true do |f|

      = f.label :title, 'title'
      br
      = f.text_field :title, class:'form-control'
      br

      = f.label :body, 'Text'
      br
      = f.text_area :body, class:'form-control'
      br

      /Postscript
      = f.label :category_id, 'Category'
      br
      = f.collection_select :category_id, Category.all, :id, :name, { prompt: 'Please select' }, class: 'form-control'
      br

      = f.submit 'Post', class: 'btn btn-primary btn-block'

  .col-xs-9
    table.table
      thead
        tr
          th
            |Contributor
          th
            |title
          th
            |Text
          /Postscript
          th
            |Category
          th

      tbody
        - @books.each do |book|
          tr
            td
              = link_to book.user  do
                = book.user.name
            td
              = link_to book.title, book_path(book)
            td
              = book.body
            /Postscript
            td
              = book.category.name
            td
              -if book.user == current_user
                = link_to 'Delete', book, method: :delete, data: { confirm: '本当にDeleteしてもよろしいですか?' }, class: 'btn-sm btn-danger'

= f.collection_select :category_id, Category.all, :id, :name ➡︎ The name of all categories is displayed in the pull-down menu, and the value is set to ʻid`.

Recommended Posts

[Rails] Implementation of category function
[Rails 6] Implementation of search function
Implementation of category pull-down function
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
[Rails] Category function
[Rails] Implementation of CSV import function
[Rails] Asynchronous implementation of like function
[Rails] Implementation of image preview function
[Rails] Implementation of user withdrawal function
[Rails] Implementation of CSV export function
[Rails] Implementation of many-to-many category functions
[Rails] gem ancestry category function implementation
[Rails] Implementation of multi-layer category function using ancestry "Preparation"
[Rails] Implementation of multi-layer category function using ancestry "seed"
[Rails] Implementation of multi-layer category function using ancestry "Editing form"
[Rails] Implementation of multi-layer category function using ancestry "Creation form"
Rails [For beginners] Implementation of comment function
[Rails 6] Implementation of SNS (Twitter) sharing function
Rails search function implementation
Implementation of pagination function
[Vue.js] Implementation of menu function Implementation version rails6
[Ruby on rails] Implementation of like function
[Vue.js] Implementation of menu function Vue.js introduction rails6
[Rails] Implementation of search function using gem's ransack
Implementation of Ruby on Rails login function (Session)
[Rails] Implementation of image enlargement function using lightbox2
[Rails] Implementation of retweet function in SNS application
Rails implementation of ajax removal
Rails fuzzy search function implementation
Implementation of sequential search function
Implementation of like function (Ajax)
Implementation of image preview function
Login function implementation with rails
[Rails 6] Pagination function implementation (kaminari)
[Rails] Implementation of drag and drop function (with effect)
Implementation of Ruby on Rails login function (devise edition)
[Ruby on Rails] Implementation of tagging function/tag filtering function
[Rails] Implementation of SNS authentication (Twitter, Facebook, Google) function
[Rails] Implementation of user logic deletion
Kaminari --Added pagination function of Rails
[Ruby on Rails] Comment function implementation
[Rails 6] Like function (synchronous → asynchronous) implementation
[Rails] Comment function implementation procedure memo
Implementation of like function in Java
Rails sorting function implementation (displayed in order of number of like)
[Rails] Implementation of tagging function using intermediate table (without Gem)
[Rails] Implementation of new registration function in wizard format using devise
[Rails] Addition of Ruby On Rails comment function
Implementation of user authentication function using devise (2)
DM function implementation
Rails Addition of easy and easy login function
[Rails 6] Ranking function
[Rails 6] Implementation of new registration function by SNS authentication (Facebook, Google)
Implementation of user authentication function using devise (1)
[Rails] Implementation of coupon function (with automatic deletion function using batch processing)
Implementation of GKAccessPoint
Rails follow function
Rails Basic CRUD function implementation procedure scaffold
Implementation of user authentication function using devise (3)
[Rails] Implementation of tag function using acts-as-taggable-on and tag input completion function using tag-it