【发布时间】:2014-11-10 23:01:24
【问题描述】:
在 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 生成的参数与强参数之间的不匹配。其中一项或两项可能不正确,但我一生都无法在网上找到示例代码来告诉我我做错了什么。
在尝试了很多失败的变体之后,我束手无策!提前感谢您的帮助!
【问题讨论】:
标签: ruby-on-rails has-and-belongs-to-many form-for strong-parameters collection-select