我需要在注册后将用户重定向回具有动态ID的特定页面。当我转到mydomain.com/registrations/11时,它会为用户帐户提取ID 11.但是当我进行新的注册时,redirect_to
行会转到没有任何ID的mydomain.com/registrations。如何使其转到为用户创建的ID?
非常感谢任何帮助。
注册控制器:
# GET /registrations
def index
@registrations = Registration.all
end
end
# GET /registrations/1
def show
end
# GET /registrations/new
def new
@registration = Registration.new
@level = Level.find_by id: params["level_id"]
end
# POST /registrations
def create
@registration = Registration.new registration_params.merge(email: params['registration']['email'],
card_token: params['registration']['card_token'])
raise "Please, check registration errors" unless @registration.valid?
@registration.process_payment(params['registration']['email'], params['registration']['card_token'])
@registration.save
redirect_to @registration, notice: 'Registration was successfully created.'
end
private
def stripe_params
params.permit :stripeEmail, :stripeToken
end
# Use callbacks to share common setup or constraints between actions.
def set_registration
@registration = Registration.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def registration_params
params.require(:registration).permit(:level_id, :firstname, :lastname, :phone, :email, :card_token)
end
路线:
get 'registrations/:id' => 'registrations#show'
get 'registrations/new' => 'registrations#new'
get 'registrations' => 'registrations#index'
修改
我能够更改使用save!
来显示异常并完成一些错误。现在我无法用Stripe解决这个问题。
错误:Stripe :: CardError(无法向没有活动卡的客户收费):
我的注册模式如下:
def process_payment(email, card_token)
customer = Stripe::Customer.create email: email,
card: card_token
Stripe::Charge.create customer: customer.id,
amount: level.price*100,
description: level.name,
currency: 'usd'
end
答案 0 :(得分:1)
提出异常不应该是应用程序正常流程的一部分。这是在控制器中处理用户输入的惯用方法:
def create
@registration = Registration.new(create_params)
if @registration.save
redirect_to @registration
else
render :new
end
end
def create_params
registration_params.merge(
email: params['registration']['email'],
card_token: params['registration']['card_token']
)
end
在处理付款时,我的经验是通常最好创建订单或其他任何内容并将其标记为未付款,然后在单独的步骤中收取付款。它使整个体验对用户来说不那么令人沮丧,因为如果你不得不通过信用卡支付门户,他们不会丢失他们可能填写的任何表格数据。
它还使应用程序逻辑更容易,因为您不必在事务中包装每个结帐步骤,并且可以轻松实现重复付款尝试或拆分付款。