1

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.

2
  • 1
    Should Classroom.where(code: row[0]).pluck(:id) be Classroom.where(code: row[0]).pluck(:id).first??? The first one will give you the room_id wrapped in an array. Commented Jun 19, 2016 at 23:32
  • 1
    @br3nt yeah, fixed. Thank you Commented Jun 19, 2016 at 23:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

So if I use this method, how can I return all the errors to my view?
@gumaro: you can use reject or select instead of each to collect instances that failed or succeeded to be saved.
records_with_errors = @reservations.reject {|r| r.save }
This is all in the create_import action. So, your success condition where all reservations are successfully imported is if there are no records with errors. That happens when reservations_with_errors.empty? returns true. If you want to check if there are errors, you can use reservations_with_errors.any? instead.
@gumaro: then you can use partition method instead of select/reject, which should give your two collections, the one that has proceeded to the db, and the one that has failed save method.
|

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.