Search code examples
ruby-on-railsrubyruby-on-rails-5rails-activerecord

Update Multiple Records with a single command in Ruby


Basically I want to update an array of objects that my api recieves in a single command. I have done it when I was inserting but I couldn't find a way to do update it. Here is m create method for multiple insertions:

def create_all

    if Attendance.create attendance_params
        render json: { message: "attendance added" }, status: :ok
    else
        render json: { message: "error in creation" }, status: :bad_request
    end
end

Params:

def attendance_params
    params.require(:attendance).map do |p|

        p.permit(
            :student_id,
            :id,
            :attendance
        )
    end
end

I tried to do similar thing with update but it generates this error:

   Completed 500 Internal Server Error in 11ms (ActiveRecord: 2.7ms) 
   Argument Error (When assigning attributes, you must pass a hash as an argument.)

my update method is this:

def update_attendance
    if Attendance.update attendance_params
        render json: { message: "attendance updated" }, status: :ok
    end
end

Solution

  • ActiveRecord Create can take an array of hashes and create multiple records simultaneously.

    However, ActiveRecord Update cannot.

    You could potentially create an "update_batch" method on your model that allows for an array of hashes. You would have to send an array of hashes and each hash would have to include the id of the record you are updating (and allow that in your strong parameters definition). Then in your update_batch method you would have to grab the id from each hash and update each:

    class Attendance < ActiveRecord
      def update_batch(attendance_records)
        attendance_records.each do |record|
          Attendance.find(record[:id]).update(record.except(:id))
        end
      end
    end