Rails コンソールで、以下のモデルを使用して、グレードK
、1
、および2
を、編集フォームにこの選択フィールドがある学校に接続しました。
ご覧のとおり、関連付けによってフィールド内の 3 つの項目が正しく選択されますが、クリックして成績を選択または選択解除すると、それらの変更は保存されません。
モデルは次のとおりです。
# app/models/school.rb
class School < ActiveRecord::Base
has_many :grades_schools, inverse_of: :school
has_many :grades, through: :grades_schools
accepts_nested_attributes_for :grades_schools, allow_destroy: true
end
# app/models/grades_school.rb
class GradesSchool < ActiveRecord::Base
belongs_to :school
belongs_to :grade
end
# app/models/grade.rb
class Grade < ActiveRecord::Base
has_many :grades_schools, inverse_of: :grade
has_many :schools, through: :grades_schools
end
フォームは次のようになります。
# app/views/schools/_form.html.haml
= form_for(@school) do |f|
/ <snip> other fields
= collection_select(:school, :grade_ids, @all_grades, :id, :name, {:selected => @school.grade_ids, include_hidden: false}, {:multiple => true})
/ <snip> other fields + submit button
コントローラーは次のようになります。
# app/controllers/schools_controller.rb
class SchoolsController < ApplicationController
before_action :set_school, only: [:show, :edit, :update]
def index
@schools = School.all
end
def show
end
def new
@school = School.new
@all_grades = Grade.all
@grades_schools = @school.grades_schools.build
end
def edit
@all_grades = Grade.all
@grades_schools = @school.grades_schools.build
end
def create
@school = School.new(school_params)
respond_to do |format|
if @school.save
format.html { redirect_to @school, notice: 'School was successfully created.' }
format.json { render :show, status: :created, location: @school }
else
format.html { render :new }
format.json { render json: @school.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @school.update(school_params)
format.html { redirect_to @school, notice: 'School was successfully updated.' }
format.json { render :show, status: :ok, location: @school }
else
format.html { render :edit }
format.json { render json: @school.errors, status: :unprocessable_entity }
end
end
end
private
def set_school
@school = School.find(params[:id])
end
def school_params
params.require(:school).permit(:name, :date, :school_id, grades_attributes: [:id])
end
end
collection_select
私の問題の核心は、によって生成されたパラメーターと強力なパラメーターの間の不一致に関係していると感じています。これらのいずれかまたは両方が間違っている可能性がありますが、私が間違っていることを示すサンプルコードをオンラインで見つけることはできません。
失敗したバリエーションをたくさん試した後、私は頭がおかしくなりました!よろしくお願いします。