首页 > 解决方案 > 参数未传递任何内容或传递 null

问题描述

付款控制器:

class PaymentsController < ApplicationController
  before_action :authenticate_user!
  def show
    @user = current_user
    @orders = Order.where(user_id: @user.email)
    @products = Product.all
  end

  def create
    @product = Product.find(params[:product_id])
    token = params[:stripeToken]
    # Create the charge on Stripe's servers - this will charge the user's card
    price = @product.avgprice.to_i*100
    @user = current_user
    begin
      charge = Stripe::Charge.create(
        amount: price,
        currency: "gbp",
        source: token,
        description: params[:stripeEmail],
        reciept_email: @user.email
      )

      if charge.paid
        Order.create(product_id: @product.id, user_id: @user.email, total: price)
      end
    rescue Stripe::CardError => e
      #The card has been declined
      body = e.json_body
      err = body[:error]
      flash[:error] = "Unfortunately, there was an error processing your payment: #{err[:message]}"
    end
    redirect_to(payments_show_path)
  end
end

_stripe_checkout_button.html:

<%price = @product.avgprice.to_i * 100%>
<form action="your-server-side-code" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="<%= Rails.configuration.stripe[:publishable_key] %>"

    data-amount="<%=price%>"
    data-name= "<%=@product.name%>"
    data-description="<%=@product.description%>"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto"
    data-currency="gbp">

  </script>
  <%= hidden_field_tag(:product_id, @product.id)%>
</form>

显示.html.erb:

<%= form_with(url: '/payments/create') do |form| %>
<%= render partial: 'shared/stripe_checkout_button'%>
<% end %>

我希望 <%= hidden_​​field_tag(:product_id, @product.id)%> 将产品 ID 传递给@product = Product.find(params[:product_id]). 但它似乎不起作用。有什么帮助吗?我从中得到的一个错误是:ActiveRecord::RecordNotFound in PaymentsController#create Couldn't find Product without an ID

标签: javascripthtmlruby-on-railsrubyheroku

解决方案


好的,我和我的导师找到的解决方案是将值更改为非动态值。我不明白为什么会这样,但确实如此:

感谢一路上帮助过的每一个人


推荐阅读