【发布时间】:2017-01-05 22:07:43
【问题描述】:
我正在努力让这个工作。我有三个模型
- 学生
- 教室注意
- 教室
使用 has_many :through 关系。我的所有关系都已正确定义,并且我已经使用 Accept_nested_attributes 设置了嵌套表单。
因此,在创建新学生时,我想从教室列表中进行选择,而不是创建新教室。表单部分也可以正常工作,但我没有得到的部分是当我创建学生时它抱怨以下错误。
无法为 ID=3 的学生找到 ID=3 的 Classrooom
我已经搜索了几天,但找不到我需要的答案。
def new
@student = Student.new
@student.classrooms.build
end
def edit
end
def create
@student = Student.new(student_params)
respond_to do |format|
if @student.save
format.html { redirect_to @student, notice: 'Student was successfully created.' }
format.json { render :show, status: :created, location: @student }
else
format.html { render :new }
format.json { render json: @student.errors, status: :unprocessable_entity }
end
end
end
这里有人可以帮忙吗,以前必须有人面对这个问题吗?
当我运行以下命令时,它也可以在 rails 控制台中工作:
classroom = Classroom.last
student = Student.create(name: 'Dave', classrooms:[classroom])
【问题讨论】:
-
从那个空白 ID 看,好像您没有获得学生字段。如何定义“student_params”?我希望看到更像 params[:student] 的东西。
-
学生参数在控制器中定义如下: def student_params params.require(:student).permit(:name, chinese_attributes:[:id, :name ]) end @elc
标签: ruby-on-rails ruby-on-rails-4 nested-forms