gumaro gumaro - 1 year ago 64
Ruby Question

Save an array of ActiveRecords objects

I'm trying to save an array of ActiveRecords in my controller, but this error is showing up:

undefined method 'save' for #

I have this method of model:

def self.import(file)
reservations = []
CSV.foreach(file, headers: true ) do |row|
room_id = Classroom.where(code: row[0]).pluck(:id).first
row[0] = room_id
reservations << row[1], check_in_date: row[2], check_out_date: row[3], room_id: row[0])

And I have this following controller:

def create_import
@reservations = Reservation.import(params[:file].path)
respond_to do |format|
format.html { redirect_to @reservation, notice: 'Reservations was successfully created.' }
format.json { render :show, status: :created, location: @reservation }
format.html { render :import }
format.json { render json: @reservations.errors, status: :unprocessable_entity }

How can I do this save method? I want to show a report with errors in my view.

Answer Source

Well, you should call save method on each of them:


Or install some third party gem that provides a multiple insert feature. You should also rewrite your if statement, since the expression above will always return the collection itself, thus evaluating to true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download