・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
The following has been implemented.
・ Slim introduction ・ Introduction of Bootstrap3 ・ Implementation of posting function ・ Category function implementation
Terminal
$ rails g model BookCategory book_id:integer category_id:integer
Terminal
$ rails db:migrate
schema.rb
create_table "book_categories", force: :cascade do |t|
t.integer "book_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Terminal
$ rails g migration RemoveCategoryIdFromBooks category_id:integer
~_remove_category_id_from_books
class RemoveCategoryIdFromBooks < ActiveRecord::Migration[5.2]
def change
remove_column :books, :category_id, :integer
end
end
Terminal
$ rails db:migrate
book.rb
has_many :book_categories
has_many :categories, through: :book_categories
category.rb
has_many :book_categories
has_many :books, through: :book_categories
book_category.rb
#Postscript
belongs_to :book
belongs_to :category
Make category_id
arrayable with the strong parameter of books_controller.rb
.
books_controller.rb
def book_params
params.require(:book).permit(:title, :body, { category_ids: [] })
end
** ① Edit the form **
slim:books/index.html.slim
/Change before
= f.label :category_id, 'Category'
br
= f.collection_select :category_id, Category.all, :id, :name, { prompt: 'Please select' }, class: 'form-control'
br
/After change
= label_tag 'Category'
br
= collection_check_boxes(:book, :category_ids, Category.all, :id, :name) do |cb|
= cb.label { cb.check_box + ' ' + cb.text }
br
= collection_check_boxes(:book, :category_ids, Category.all, :id, :name) do |cb|
➡︎ The names of all categories are displayed as checkboxes and the value is set to id.
** ② Edit the table **
slim:books/index.html.slim
/Change before
td
= category.name
/After change
td
- book.categories.each do |category|
= category.name
| /
Recommended Posts