我在Rails中很新。在我使用Stripe的项目中,我一直试图收费。但每当我尝试运行它时,我都会遇到此错误。我花了两天时间阅读和搜索,但我不知道它有什么问题:
ActiveRecord::RecordNotFound in ChargesController#create
Couldn't find Product with 'id'=
Extracted source (around line #39):
def amount_to_be_charged
@amount = Product.find(params[:id]).unit_price * 100
end
致电的代码。 app/views/products/index.html.erb
<%= link_to 'Buy', new_charge_path(id: x.id), class:"btn btn-primary"%>
我的控制器app/controllers/charges_controller.rb
class ChargesController < ApplicationController
before_action :authenticate_user!
before_action :amount_to_be_charged
before_action :description
def thanks
end
def new
end
def create
customer = StripeTool.create_customer(
email: params[:stripeEmail] ,
stripe_token: params[:stripeToken]
)
charge = StripeTool.create_charge(
customer_id: customer.id,
amount: @amount,
description: @description
)
redirect_to thanks_path
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
private
def amount_to_be_charged
@amount = Product.find(params[:id]).unit_price * 100
end
def description
@description = Product.find(params[:id]).description
end
end
我的路线
Rails.application.routes.draw do
get 'thanks', to: 'charges#thanks', as: 'thanks'
resources :charges, only: [:new, :create]
resources :sales
resources :invoices
resources :products
resources :categories
devise_for :users
root 'products#index'
end
更新
我的new.html.erb
<h1>Charges</h1>
<%= form_tag charges_path do %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>Amount: <%= formated_amount(@amount) %> </span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="<%= @description %>"
data-amount="<%= @amount %>"
data-email="<%= current_user.email %>"
data-bitcoin="true"
data-locale="auto"></script>
<% end %>
看起来像这样:
如您所见,数量正确就位。
我的thanks.html.erb
<h2>Thank you for your payment!</h2><br>
<p>
Your payment of <strong><%= formated_amount(@amount) %></strong> has been sent.
</p>
答案 0 :(得分:1)
似乎params[:id]
为零,before_action :amount_to_be_charged
在每个操作之前运行,并尝试通过提取产品来确定价格。最有可能redirect_to thanks_path
缺少id参数,请尝试:redirect_to thanks_path(id: params[:id])
。
提示:我建议您在此处使用更具描述性的命名,而不是使用id
使用product_id
答案 1 :(得分:1)
您是否明确将id
行动中的#new
传递给#create
?
通过以下方式:
new_charge_path(id: x.id)
,其中x
可能是“产品”charges#new
,此时id
应该在params
中,符合预期new.html.erb
看起来是什么样的,并且它将id
字段的值设置为params[:id]
的值?答案 2 :(得分:0)
要进行调试,请查看日志以查看发送到控制器的params散列。另请查看源代码以查看x.id等于什么。尝试以不同的格式发送ID:
<%= link_to 'Buy', new_charge_path, id: x.id, class:"btn btn-primary"%>
答案 3 :(得分:0)
我认为问题出在 redirect_to thanks_path 行中,你在这里尝试做的是重定向到索引操作但是,你有一个before_action过滤器,一旦重定向发生就会被执行< strong> amount_to_be_charged 但是, params 哈希是空的,因为在重定向期间没有传递任何值。如果您希望 amount_to_be_charged 和描述过滤器仅在创建期间运行,请对此进行排序,然后更改 before_action 如下,
before_filter :amount_to_be_charged, only: [:create]
before_filter :description, only: [:create]