1

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

apparently this is working but I got forbidden attributes error. although I have defined strong attributes and have used them like this: StudentAttendance.find(record[:id]) .update_attributes!(student_attendance_params_for_update=(record))
1

Please check this example and try applying it:

Attendance.where(:student_id => [23,45,68,123]).update_all(:attendance => true)

Or if you're trying to update all Attendance records:

Attendance.update_all(:attendance => true)

Also, please check this link: https://apidock.com/rails/ActiveRecord/Relation/update_all

1 Comment

there are multiple records to be updated by multiple entries which are received in the form of an array update_all update all records with same value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.