Ruby on rails 不确定将条带API调用放在何处
我已经思考这个问题好几个小时了,我想这是因为我误解了rails的一些基本知识 在中,他们演示了以下代码Ruby on rails 不确定将条带API调用放在何处,ruby-on-rails,stripe-payments,Ruby On Rails,Stripe Payments,我已经思考这个问题好几个小时了,我想这是因为我误解了rails的一些基本知识 在中,他们演示了以下代码 def new end def create # Amount in cents @amount = 500 customer = Stripe::Customer.create( :email => 'example@stripe.com', :card => params[:stripeToken] ) charge = Stripe
def new
end
def create
# Amount in cents
@amount = 500
customer = Stripe::Customer.create(
:email => 'example@stripe.com',
: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 charges_path
end
我的问题是,create
操作中的所有代码都必须驻留在create
中吗
我正试图遵循指南,但不是只有一个单一的产品,我有多个。因此,我自然会将代码放在show
操作中
class BooksController < ApplicationController
def index
@books = Book.all
end
def show
@book = Book.find(params[:id])
customer = Stripe::Customer.create(
:email => 'example@stripe.com',
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @book.price,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to books_path
end
end
class BooksController'example@stripe.com',
:card=>params[:stripeToken]
)
charge=Stripe::charge.create(
:customer=>customer.id,
:amount=>@book.price,
:description=>“Rails条带客户”,
:货币=>“美元”
)
救援条带::CardError=>e
闪光[:错误]=e.message
重定向到图书路径
结束
结束
现在,每当我尝试访问任何show页面(localhost:3000/books/1),它都会重定向到books\u路径
,这告诉我存在某种卡错误
这是怎么回事?因为您的
show
方法中有:
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to books_path
当您尝试通过show
操作访问任何页面时,它会尝试创建费用
,但出现错误,因此上面的代码会将其解救出来,并将您重定向到图书路径
。所以,这是很正常的行为
如果您修复了您收到的卡错误
,它将成功创建费用。但是,同样,这不是一个正确的地方来创建收费。
您应该有一个自定义控制器/视图,如教程所示,以创建电荷
在您的展示页面中,您可以有一个产品表单和一个购买产品的按钮,当按下该按钮时,您的表单应提交给自定义控制器的操作方法,您可以在其中创建费用。是的,您混淆了/混合了一些rails知识。您需要做的是:
#Create your BooksController
class BooksController < ApplicationController
def index
@book = Book.all
end
def new
@book = Book.new
end
def create
@book = Book.new(book_params)
if @book.save
#do something
else
#do something
end
end
def show
@book = Book.find(params[:id])
end
#edit
#destroy
end
您需要将sales
操作嵌套在您的routes文件中的book操作中
resources: books do
resources :sales
end
这应该会让你从正确的方向开始。谢谢你为我指明了正确的方向。两个问题,我是否需要
Sale.create(book\u id:@book.id,amount:@book.price,其他内容)
行,因为条纹指南似乎也没有数据库。其次,我按照你的建议嵌套了salescontroller。在我这方面,一切似乎都很好,但仪表板上并没有显示任何费用。你知道我做错了什么吗?是的,如果你想要一份销售记录(Stripe除外),你需要在你这边创建销售记录。Stripe确实有一个可以引用的数据库。您需要将条带密钥与对象一起存储。例如,如果用户已登录,则可以将条带客户id存储到该用户模型。然后,您可以检索附加到该客户的所有事务。您有创建条带令牌的js文件吗?
resources: books do
resources :sales
end