Kristian
Kristian

Reputation: 21840

Rails error messages always displayed, even before submit

My Account model:

  def save_with_payment
    if valid?
      customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)
      self.stripe_customer_token = customer.id
      save!
    end
  rescue Stripe::InvalidRequestError => e
    logger.error "Stripe error while creating customer: #{e.message}"
    errors.add :base, "There was a problem with your credit card."
    false
  end

My accounts controller:

  # GET /accounts/new
  # GET /accounts/new.json
  def new
    @account = Account.new
    @company = @account.build_company
    @user = @company.users.build

    if @account.save_with_payment
      redirect_to success_path, :notice => "Thank you for subscribing!"
    else
      render :new
    end

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @account }
    end

  end

For some reason (only just started happening), the form always shows the validation errors (with or without submitting first)

why is this?

Upvotes: 0

Views: 164

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30473

You execute @account.save_with_payment before submitting (and you don't pass parameters to this method). The code looks strange, usually there are two methods new and create, in first one you just find @account and pass it to view for form, in second one you save @account.

def new
  @account = Account.new
end

def create
  @account = Account.new(params[:account])

  if @account.save
    redirect_to @account
  else
    render :action => 'new'
  end
end

Upvotes: 2

Related Questions