我在保存Classroom_Students方面遇到了麻烦。表单识别正确的参数,它们不会保存到数据库中。我知道有类似的问题,但没有一个答案(我见过)解决了我的问题。
错误讯息:
未经许可的参数:student_ids
我正在尝试通过classroom_students表格将学生添加到课堂中
// Classroom.rb
has_many :classroom_students
has_many :students, through: :classroom_students
accepts_nested_attributes_for :classroom_students
// Student.rb
has_many:classroom_students has_many:教室,通过:: classroom_students
// ClassroomStudent.rb(连接表)
belongs_to :classroom
belongs_to :student
//课堂控制器
def classroom_params
params.require(:classroom).permit(:name, :description, :teacher_id,
classroom_student_attributes:[:student_ids => []])
end
顺便说一句,所有其他属性都保存在教室的数据库中。
//创建教室的表单
<%= simple_form_for @classroom do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.simple_fields_for :classroom_students do |classroom_students| %>
<%= f.association :students, as: :check_boxes %>
<% end %>
<%= f.button :submit %>
<% end %>
显示所有学生姓名,提交表格时,会在课堂下阅读。
Parameters: {"utt8"=>"✓", "authenticity_token"=>"jklqjwerqjfeiqwjrkljfa231=", "classroom"=>{"name"=>"Not Violin Class", "description"=>"It's not", "student_ids"=>["1", "3", ""]}, "commit"=>"Create Classroom"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 9]]
Unpermitted parameter: student_ids
(0.2ms) begin transaction
SQL (0.4ms) INSERT INTO "classrooms" ("name", "description", "teacher_id") VALUES (?, ?, ?) [["name", "Not Violin Class"], ["description", "Please Please Please"], ["teacher_id", 9]]
(11.2ms) commit transaction
任何反馈意见都会受到赞赏,我还没有想到这一点。谢谢。
答案 0 :(得分:1)
未经许可的参数:student_ids
您要在student_ids
哈希中发送classromm
,您需要将其发送到classroom_students
哈希
更改此
<%= f.simple_fields_for :classroom_students do |classroom_students| %>
<%= f.association :students, as: :check_boxes %>
<% end %>
到
<%= f.simple_fields_for :classroom_students do |classroom_students| %>
<%= classroom_students.association :students, as: :check_boxes %>
<% end %>
此外,classroom_student_attributes
应为classroom_students_attributes
def classroom_params
params.require(:classroom).permit(:name, :description, :teacher_id, classroom_students_attributes: [:student_ids => []])
end
<强> 更新 强>
协会:未找到学生
这是因为classroom_student
上的关联是belongs_to :student
,所以此行
<%= classroom_students.association :students, as: :check_boxes %>
应该是
<%= classroom_students.association :student, as: :check_boxes %>