【发布时间】:2017-07-11 13:56:42
【问题描述】:
所以我们有一个 has_many :through 关联。一个教室有_many Students 到 ClassroomStudents。
学生是通过classroom_new 表单以嵌套形式添加的,因此创建ClassroomStudents 需要通过Classroom Controller 而不是ClassroomStudent 控制器。
我正在创建通知,以便在将学生添加到教室时通知家长。但是无论添加多少学生,都只会创建一个通知,并且不会保存学生 ID。如何从一个表单中创建多个通知?
教室控制器创建方法(ClassroomStudenets也在这里创建)
def create
@classroom = current_user.classrooms.create(classroom_params)
@classroom_student = ClassroomStudent.new
@student = @classroom_student.student_id
respond_to do |format|
if @classroom.save
format.html { redirect_to @classroom, notice: "Classroom successfully created." }
format.json { render :show, status: :created, location: @classroom }
if @classroom_student.save
@student = @classroom_student.student_id
create_notification @classroom, @classroom_student, @student
end
else
format.html { render :new, alert: "Failed to create classroom." }
format.json { render json: @classroom.errors, status: :unprocessable_entity }
end
end
end
在课堂控制器中创建通知方法
def create_notification(classroom, classroom_student, student)
Notification.create(user_id: current_user.id,
#this is temporary, it will soon be the student.parent_id
notified_by_id: current_user.id,
student_id: classroom_student.student_id,
identifier: classroom.id,
notice_type: 'add student')
end
在控制器中定义参数
def classroom_params
params.require(:classroom).permit(:name, :image, :description, student_ids: [])
end
def classroom_students_params
params.require(:classroom_student).permit(:student_id, :classroom_id, student_ids: [])
end
课堂新形式
<title>Create a Class - Kidznotes</title>
<div class="authform">
<h2><center>Create a Classroom</center></h2>
<%= simple_form_for @classroom do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :image %>
<h6>This image will be on your classroom banner</h6>
<br>
<%= f.label :classroom_students %>
<br>
<div class="form-3-col">
<%= f.collection_check_boxes :student_ids, Student.all, :id, :first_name %>
</div>
<br>
<%= f.button :submit %>
<% end %>
class Notification
belongs_to :student
belongs_to :notified_by, class_name: 'User'
end
班级有很多通知,用户也有,但课堂学生或学生没有(学生是帐户类型,他们被视为父母创建的对象)
这是保存在数据库中的内容:
#<Notification id: 21, user_id: 3, notified_by_id: 3, post_id: nil, identifier: 76, notice_type: "add student", read: false, created_at: "2017-07-11 13:54:11", updated_at: "2017-07-11 13:54:11", student_id: nil>
我被困在这个问题上的时间比我想承认的要长,所以提前感谢任何反馈。
【问题讨论】:
-
您可能有一个验证错误,导致您对
create的调用不成功。尝试将您对create(...)的调用替换为create!(...),以便在您尝试调试时引发异常并向您显示验证失败的位置(并且未保存记录)。
标签: ruby-on-rails