Cameron Bass Cameron Bass - 1 month ago 7
Ruby Question

Fixing a Double Render Error when creating more than one object with one request

Right now I have a controller action that takes in an array. It iterates through the array and should make a new object of each element in the array. But when I attempt this now I get a double render error? Anyone know how I can fix this?

Controller



def create
params[:emails].each do |email|
# Ignore if the user is already on the account.
if current_account.users.exists?(email: email) || current_account.invitations.exists?(email: email)
flash[:alert] = "#{email} is already on the team"
redirect_to account_users_path

return
end

invitation = Invitation.new({
account: current_account,
inviter: current_user,
email: email,
})

if invitation.save
Notifier.invite(invitation).deliver_later
else
flash[:alert] = "Email is invalid"
end

redirect_to account_users_path
end
end


As you can see I iterate over the emails and try to make a new object out of each. But right now I get this error.

AbstractController::DoubleRenderError in Accounts::InvitationsController#create

Answer

Move the redirect_to call outside the loop:

def create
  params[:emails].each do |email|
    # Ignore if the user is already on the account.
    if current_account.users.exists?(email: email) || current_account.invitations.exists?(email: email)
      flash[:alert] = "#{email} is already on the team"
      redirect_to account_users_path

      return
    end

    invitation = Invitation.new({
      account: current_account,
      inviter: current_user,
      email:   email,
    })

    if invitation.save
      Notifier.invite(invitation).deliver_later
    else
      flash[:alert] = "Email is invalid"
    end
  end
  redirect_to account_users_path
end
Comments