将查询字符串从#new 传递到#create

Passing query string from #new to #create

我正在尝试在 Stripe 交易后更新我的库存

路线:

  get 'product/:size' => 'charges#new'
  resources :charges 

例如:localhost:3000/product/32

控制器

  def new
    @product = Product.find_by(size: params[:size])
  end

  def create
    @amount = 500
    @product = Product.find_by(size: params[:size])
    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'
    )


    @product.update_attribute(:status, "sold")

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


  end
end

这个returns

undefined method `update_attribute' for nil:NilClass

经过反复试验,我认为问题是Rails没有在参数中找到[:size],因此实例变量没有被实例化。

我必须做什么?

确保将 :size 参数包含到您的表单中,以便在 POST 期间将其传递给创建操作。您可以使用 hidden_field_tag:

将其包含在您的表单中
<%= form ... do %>
  <%= hidden_field_tag :size, params[:size] %>

  Other form inputs....
<% end %>