使用form_for和form_tag,同时仍然传递params

时间:2014-06-24 18:45:47

标签: ruby-on-rails ruby ruby-on-rails-4 stripe-payments form-for

这可能是一个简单的,但寻找一些澄清,以便我能理解正在发生的事情。我使用条带进行付款,并使用form_tag

设置表单
<%= form_tag donations_path, id: 'payment-form' do %>

<%= text_field_tag :email, nil, placeholder: "Email Address", class: 'form-control', :data => {:stripe => 'email' } %>

<%= text_field_tag :card_number, nil, name: nil, :placeholder => "Card Number",  class: 'form-control', :data => {:stripe => 'number' } %>

 <!--More fields here-->

<% end %>

现在通过此控制器提交此表单

class DonationsController < ApplicationController
def new
end

def create

@amount = params[:donation_amount].to_i
# Create the Customer Object 
customer = Stripe::Customer.create(
  :email => params[:email],
  :card  => params[:stripeToken]
)

charge = Stripe::Charge.create(
:customer    => customer.id,
:amount      => @amount,
:description => 'Rails Stripe customer',
:currency    => 'usd'
)

 rescue Stripe::CardError => e
   flash[:error] = e.message
   redirect_to donations_path
 end


private

 def donation_params
  params.require(:donation).permit(:id, :campaign_id, :name, :email, :message, :donation_amount)
end
end

传递的参数是

authenticity_token  randomtokenhere
email   richlewis14@gmail.com   
stripeToken tok_104HXi4DL3s6WpXhX5bTCxMW
utf8    ✓

如果我将表单更改为form_for并使用以下表单,则不再生成stripeToken

authenticity_token  randomtokenhere
email   richlewis14@gmail.com   
utf8    ✓

我想知道如何让这个工作

新表格

<%= form_for @donation, id: 'payment-form' do |f| %>

<%= f.text_field :email, placeholder: "Email Address", class: 'form-control', :data => {:stripe => 'email' } %>

<%= text_field_tag :card_number, nil, name: nil, :placeholder => "Card Number",  class: 'form-control', :data => {:stripe => 'number' } %>

 <!--More fields here-->

<% end %>

NEW Controller

class DonationsController < ApplicationController
def new
  @donation = Donation.new
end

def create
@dontation = Donation.new(donation_params)
@amount = params[:donation][:donation_amount].to_i
# Create the Customer Object 
customer = Stripe::Customer.create(
  :email => params[:donation][:email],
  :card  => params[:stripeToken]
)

charge = Stripe::Charge.create(
:customer    => customer.id,
:amount      => @amount,
:description => 'Rails Stripe customer',
:currency    => 'usd'
)

 rescue Stripe::CardError => e
   flash[:error] = e.message
   redirect_to donations_path
 end


private

 def donation_params
  params.require(:donation).permit(:id, :campaign_id, :name, :email, :message, :donation_amount)
end
end

我错过了一些简单的确定但是如果有人能指出什么会非常感激

感谢

1 个答案:

答案 0 :(得分:1)

虽然你没有提到这一点,但我想stripeToken是由一些依赖于找到form#payment-form的javascript添加的,对吧?

因此,您的错误可能是,您的第二个form无法获得正确的ID。

使用form_for时,您必须传递如下的html属性:

<%= form_for @donation, html: { id: 'payment-form' } do |f| %>
  ...
<% end %>
PS:你的第二个控制器中有一个拼写错误&#39;创建&#39;方法(@dontation代替@donation