我想模拟学生的出勤率,我正在关注railscast.com/165-edit-multiple-revised我遵循Ryan的第一种方法并尝试将其用于mongoid。我修改后的代码如下,但它不更新多条记录,甚至不更新任何记录。听起来像mongoid没有找到任何ID为数组的学生。请看代码,让我知道我做错了什么。
# config/routes.rb
resources :students do
collection do
put :attendance
end
end
# model/student.rb
class Student
include Mongoid::Document
field :name, type: String
field :present, type: Mongoid::Boolean
end
# controllers/students_controller.rb
def attendance
Student.where(id: params[:student_ids]).update_all(present: true)
redirect_to students_url
end
# views/students/index.html.erb
<% @students.each do |student| %>
<tr>
<td><%= check_box_tag "student_ids[]" , student.id %></td>
<td><%= student.name %></td>
<td><%= student.present %></td>
<td><%= link_to 'Show', student %></td>
<td><%= link_to 'Edit', edit_student_path(student) %></td>
<td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
如果我按照以下方式更改控制器中的代码,但它对此代码不满意。有没有其他方法或我做错了什么?
# controllers/students_controller.rb
def attendance
params[:student_ids].each do |student_id|
Student.where(id: student_id).update_all(present: true)
end
redirect_to students_url
end
答案 0 :(得分:3)
如果您想要获取一组学生,您应该尝试使用 in 运算符。试试这个:
def attendance
Student.where(:id.in => params[:student_ids]).update_all(present: true)
redirect_to students_url
end
您怎么看?