0

在 rails 控制台并使用以下模型,我将 Grades K1和连接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参数和强参数之间的不匹配有关。其中一项或两项可能不正确,但我一生都无法在网上找到示例代码来告诉我我做错了什么。

在尝试了许多失败的变化之后,我束手无策!在此先感谢您的帮助!

4

1 回答 1

0

废话。我本可以发誓我以前尝试过这个,但它一定是在使用fields_for表单而不是collection_select. 解决方案:

def school_params
  params.require(:school).permit(:name, :date, :school_id, grades_attributes: [:id])
end

变成

def school_params
  params.require(:school).permit(:name, :date, :school_id, grade_ids: [])
end

我仍然很好奇它在使用时会如何工作fields_for @grades_schools,但必须将调查留到另一天......

于 2014-11-10T23:23:30.287 回答