在 rails 控制台并使用以下模型,我将 Grades 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
参数和强参数之间的不匹配有关。其中一项或两项可能不正确,但我一生都无法在网上找到示例代码来告诉我我做错了什么。
在尝试了许多失败的变化之后,我束手无策!在此先感谢您的帮助!