2013-04-30 46 views
0

我的賬戶模型:Rails的錯誤信息一直顯示,甚至在提交

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 

我的賬戶控制:

# 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 

出於某種原因(纔剛剛開始發生),表單總是顯示驗證錯誤(有或沒有先提交)

這是爲什麼?

+2

你的'save_with_payment'方法有什麼作用?它看起來會試圖保存'@ account',並且驗證失敗。你確定這種行爲不應該在「創造」行動嗎?否則,對於方法和驗證來說,很高興看到你的'Account'模型。 – 2013-04-30 02:34:06

+0

我添加了模型 – Kristian 2013-04-30 05:21:52

回答

2

您在提交之前執行@account.save_with_payment(並且您不會將參數傳遞給此方法)。代碼看起來很奇怪,通常有兩種方法newcreate,第一種方法是找到@account並將其傳遞給窗體查看,第二種方法是保存@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 
+0

哦,有趣。如果我有3個相關模型正在構建,我應該怎麼做?仍然都在創建方法? – Kristian 2013-04-30 05:44:13