0
votes

I have a Rails page that lets the user select one or more records.

This is the controller action:

  def addinvtimes
    @invoice = params[:invtimes][:invoice_id]
    if params[:event_ids] != nil
      params[:event_ids].each do |i|
        newinvtime = Invtime.new(
            linetype_id: 1,
            invoice_id: @invoice,
            event_id: i.to_i
        )
        if newinvtime.save
          respond_to do |format|
            if newinvtime.save
              format.html { redirect_to invoice_path(@invoice), :notice => 'Invoice Item was successfully added.' }
            else
              format.html { redirect_to invoice_path(@invoice), :notice => 'ERROR.' }
            end
          end
        end
      end
    end
  end

There error I get is:

Render and/or redirect were called multiple times in this action

How can I code to not call the redirect multiple times?

1

1 Answers

2
votes

Your actual problem is not in the double/redirect error, but in the logic. Assume the params[:event_ids] contain 1000 items. Is where it should to be redirected?

 params[:event_ids].each do |i|
   if something.save
        redirect_to .....
     else
        redirect_to .....
    end
 end

You can redirect only once at an action call, but you trying to call redirect in each step of the iterator, I am pretty sure you can't do this.