Select multiple checkboxes and implement the tagging function via the intermediate table.
・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
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.
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