In a many-to-many model relationship, I want to register multiple selected values in the intermediate table with the check box. I was really into it when I implemented it, so I'll leave it as a memorandum.
Rails 5.2
Ruby 2.5.1
MacOSX
--Project model
class Project < ApplicationRecord
has_many :project_phases, dependent: :destroy
has_many :mst_phases, through: :project_phases
end
--Project process
class ProjectPhase < ApplicationRecord
belongs_to :project
belongs_to :mst_phase
end
--Process master
class MstPhase < ApplicationRecord
has_many :project_phases
end
Regarding the process, only the project_phase
model is associated in the master table so that the project model side is not referenced.
View
<%= form_with model: @project, local: true do |f| %>
<label>Project name</label>
<%= f.text_field :project_name %>
<label>Project process</label>
<%= f.collection_check_boxes :mst_phase_ids, MstPhase.all, :id, :phase %>
<% end %>
Controller
class ProjectsController < ApplicationController
def new
@project = Project.new
@project.project_phases.build
end
def create
@project = Project.new(projects_params)
if @project.save
redirect_to project_path @project
else
render action: 'new'
end
end
private
def projects_params
params.require(:project).permit( :project_name, mst_phase_ids: [])
end
end
The point is to set StrongParameter
to receive models related to has_many
as an array.
The names of the parameters should be described as follows.
Model name_ids
Since it is not necessary to implement any special logic for the parameters received in the array, records are registered in the table for the number of elements in the array. Rails convenient. .. .. .. ..
Recommended Posts