我已经尝试了几个小时来解决这个问题。我可以在我的付款模式payment.rb中成功使用此代码付款:
def save_with_payment
if valid?
customer = Stripe::Customer.create(description: email, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
Stripe::Charge.create(
:amount => (total * 100).to_i, # in cents
:currency => "usd",
:customer => customer.id
)
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
我想在我的用户模型中将Stripe的customer.id保存到我的用户表属性customer_id,但上面的代码在我的付款模式中,我该怎么做?
Stripe的帮助部分说,通过执行以下操作很容易:
save_stripe_customer_id(user, customer.id)
然后:
customer_id = get_stripe_customer_id(user)
Stripe::Charge.create(
:amount => 1500, # $15.00 this time
:currency => "usd",
:customer => customer_id
)
我在save_stripe_customer_id中输入了什么代码?我在哪里放这个代码?上面生产Stripe的customer.id的方法在付款模式中,但我希望将其保存为我的用户模型中的属性,这样我就可以在以后向用户收费,而无需重新输入信用卡。如何将付款模式中生成的内容保存到我的用户表中?
编辑:
payment.rb
belongs_to :user
user.rb
has_many :payments
我要作为customer_id添加到users表的属性已作为stripe_customer_token存在于我的付款表中,我无法弄清楚如何在那里使用它或如何将其传输到我的users表。
MORE:
payments_controller.rb:
def create
if current_user
@payment = current_user.payments.new(params[:payment])
else
@payment = Payment.new(params[:payment])
end
respond_to do |format|
if @payment.save_with_payment
format.html { redirect_to @payment, notice: 'Payment was successfully created.' }
format.json { render json: @payment, status: :created, location: @payment }
else
format.html { render action: "new" }
format.json { render json: @payment.errors, status: :unprocessable_entity }
end
end
end
原因可能是
self.user.update_attribute(customer_id, customer.id)
为customer_id抛出一个未定义的方法,以某种方式与Devise相关,因为用户参与其中?我的路线文件中是否需要更改内容?
的routes.rb
devise_for :users, :path => 'accounts' do
get 'users', :to => 'store#index', :as => :user_root
end
resources :users
resources :payments
match ':controller(/:action(/:id))(.:format)'
答案 0 :(得分:2)
试试这个
def save_with_payment
if valid?
customer = Stripe::Customer.create(description: email, card: stripe_card_token)
self.stripe_customer_token = customer.id
self.user.update_attribute(:customer_id, customer.id) #this will update your user
save!
Stripe::Charge.create(
:amount => (total * 100).to_i, # in cents
:currency => "usd",
:customer => customer.id
)
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