我添加了一个if语句来查看教师计数是否上升,因为这是classroom_show并且它如果刷新页面或重定向到页面,则会自动创建通知。我认为计数可以确保保存新条目
课堂控制器(正在执行的操作)
@classroom_teacher = ClassroomTeacher.new
if @classroom_teacher.save && @classroom.teachers.count +=1
@classroom.teachers.each do |teacher|
create_teacher_notification @classroom, teacher
end
end
当我尝试转到该页面时,它会给我一个错误。
NoMethodError未定义方法`count ='for
你的意思是?计数
有没有更好的方法来确保课堂教师实际上已经创建?我不希望它是独一无二的,因为教师可以读到教室。我尝试了一些事情。
@classroom_teacher = ClassroomTeacher.build
和
@classroom_teacher = ClassroomTeacher.create
不起作用,因为这里没有为它们定义构建和创建,但它们确实成功保存。
答案 0 :(得分:1)
NoMethodError未定义方法`count ='对
上述错误的原因是:
您正试图在count=
上调用@classroom.teachers
方法,该方法将返回ActiveRecord
集合
@classroom.teachers.count += 1 # is actually short hand for
@classroom.teachers.count = @classroom.teachers.count + 1
您尝试实现的目标可以通过更改此
来完成count = @classroom.teachers.count # Save the teachers count in a variable
# Compare the count after save with the previous count
if @classroom_teacher.save && @classroom.teachers.count == count + 1
@classroom.teachers.each do |teacher|
create_teacher_notification @classroom, teacher
end
end
答案 1 :(得分:1)
看起来有一个关联,即课堂上有很多人:老师 - 就是这样吗?
如果是这样,我会:
@classroom.teachers.new
if @classroom.save
@classroom.teachers.each do |teacher|
create_teacher_notification @classroom, teacher
end
end
如果新关联未保存,则保存将返回false。