[Rails] Implementation of tagging function using intermediate table (without Gem)

Goal

Select multiple checkboxes and implement the tagging function via the intermediate table.

Development environment

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

E-R diagram

スクリーンショット 2020-12-21 10 58 14 The above image is the image to be implemented this time. This time, I will talk about an example of selecting and registering multiple types of saunas that I have implemented.

Advance preparation

We have prepared a screen to create a new sauna like the one in the image. In this talk, we will use the `method of selecting multiple checkboxes in the sauna genre and implementing it using the sauna genre, which is an intermediate table. I will talk about basic functions such as registration function on the assumption that they have already been implemented. スクリーンショット 2020-12-21 11 07 41

Describe the association in the model

app/models/sauna.rb


class Sauna < ApplicationRecord
  has_many :sauna_genres, dependent: :destroy
  has_many :genres, through: :sauna_genres
end

app/models/sauna_genre.rb


class SaunaGenre < ApplicationRecord
  belongs_to :genre
  belongs_to :sauna
end

app/models/genre.rb


class Genre < ApplicationRecord
  has_many :sauna_genres
  has_many :saunas, through: :sauna_genres
end

controller

app/controllers/saunas_controller.rb


  def create
    @sauna = Sauna.new(sauna_params)
    @sauna.user_id = current_user.id
    if @sauna.save
      redirect_to user_sauna_path(@sauna)
    else
      render 'new'
    end
  end

 #abridgement

   def sauna_params
    params.require(:sauna).permit(
      :name,
      genre_ids: []
    )
  end

genre_ids: [] allows multiple checkbox values ​​to be passed as an array.

html.erb


<div>
  <%=f.label :genre_ids, "Genre function" %>
  <span>
    <% Genre.all.each do |genre| %>
      <%= f.check_box :genre_ids, 
         { multiple: true, checked: @sauna.genres.find_by(id: genre.id).present?, 
         include_hidden: false }, genre[:id] %>
       <label class="form-check-label">
         <%= genre.name %>
       </label>
     <% end %>
  </span>
</div>

form.check_box: label_ids → As the value of params,"label_ids" => ["1", "2", "3"]You can send a value with a hash key in this way. You can send parameters for multiple checkboxes in an array format by using the multiple option. checked: @ task.labels.find_by (id: label.id) .present? This is to check the label registered on the edit screen etc. include_hidden: false → This method does not send parameters for items that are not registered.

*** If you implement it as it is, you can create multiple intermediate tables at first glance, and I thought that there is no problem because it is checked firmly when editing ***, but even if you uncheck all the checks on the edit screen and update it, the genre Multiple names did not disappear. What is the cause? With this implementation method, nil will be returned as a value if you send it empty ***. *** *** To solve it, we will devise a little strong parameter.

app/controllers/saunas_controller.rb


#abridgement

  def sauna_params
    values = params.require(:sauna).permit(
      :name,
      genre_ids: []
    )
    if values[:genre_ids].nil?
      values[:genre_ids] = [] 
    end
    return values
  end

By doing this, I was able to create something that does not have a genre by sending an empty array to genre_ids when nil is returned. As long as I'm making a genre, I don't think there is no genre, but I noticed it, so I'll leave it as a memorandum.

Thank you very much

Recommended Posts

[Rails] Implementation of tagging function using intermediate table (without Gem)
[Rails] Implementation of search function using gem's ransack
[Rails 6] Implementation of inquiry function using Action Mailer
[Rails] Implementation of image enlargement function using lightbox2
[Rails] Implementation of batch processing using whenever (gem)
[Rails 6] Implementation of search function
[Rails] Implementation of category function
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
[Ruby on Rails] Implementation of tagging function/tag filtering function
[Rails] Implementation of multi-layer category function using ancestry "Preparation"
[Rails] Implementation of multi-layer category function using ancestry "seed"
[Rails] Asynchronous implementation of like function
[Rails] Implementation of image preview function
[Rails] Implementation of multi-layer category function using ancestry "Creation form"
[Rails] About implementation of like function
[Rails] gem ancestry category function implementation
[Rails] Implementation of coupon function (with automatic deletion function using batch processing)
[Rails] Implementation of tag function using acts-as-taggable-on and tag input completion function using tag-it
Implementation of user authentication function using devise (2)
Implementation of user authentication function using devise (1)
Rails [For beginners] Implementation of comment function
[Rails 6] Implementation of SNS (Twitter) sharing function
Implementation of user authentication function using devise (3)
[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
Implementation of Ruby on Rails login function (Session)
Story of implementing login function using gem sorcery
[Rails] Implementation of retweet function in SNS application
[Rails] Implementation of PV number ranking using impressionist
[Rails] Implementation of image slide show using Bootstrap 3
[Note] Summary of rails login function using devise ①
[Rails] Implementation procedure of the function to tag posts without gem + the function to narrow down and display posts by tags
[Rails] Set validation for the search function using Rakuten API (from the implementation of Rakuten API)
Implementation of search function
Rails search function implementation
Implementation of pagination function
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Rails] Implementation of drag and drop function (with effect)
[Rails] Test of star evaluation function using Raty [Rspec]
Implementation of Ruby on Rails login function (devise edition)
[For Rails beginners] Implemented multiple search function without Gem
[Rails] Implementation of SNS authentication (Twitter, Facebook, Google) function
Try to implement tagging function using rails and js
[Ruby on Rails] How to implement tagging / incremental search function for posts (without gem)
Rails implementation of ajax removal
Rails fuzzy search function implementation
Search function using [rails] ransack
[Rails] Implementation of automatic address input using jpostal and jp_prefecture
Implementation of sequential search function
Implementation of like function (Ajax)
Implementation of image preview function
Rails sorting function implementation (displayed in order of number of like)
[Rails] Implement event end function (logical deletion) using paranoia (gem)
Implementation of category pull-down function
Login function implementation with rails
Ajax bookmark function using Rails
[Rails 6] Pagination function implementation (kaminari)
Implement a refined search function for multiple models without Rails5 gem.
[Rails] Sign-up function using devise error number of arguments (given 0, expected 1)