gumaro
gumaro

Reputation: 67

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 #<Array:...>

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 << Reservation.new(number_of_guests: row[1], check_in_date: row[2], check_out_date: row[3], room_id: row[0])
  end
  reservations
end

And I have this following controller:

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

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

Upvotes: 1

Views: 556

Answers (1)

potashin
potashin

Reputation: 44581

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

@reservations.each(&:save)

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.

Upvotes: 2

Related Questions