问题
I am just learning RoR and need I am having trouble with Stripe integration. I have done everything as it says here except I have changed "charges" to "charge."
The error I am receiving is:
No route matches {:action=>"show", :controller=>"charge"} missing required keys: [:id]
.
It's not letting me do: <%= form_tag charge_path do %>
This is my controller:
class ChargeController < ApplicationController
def new
end
def create
# Amount in cents
@amount = 0
customer = Stripe::Customer.create(
:email => 'jon@jonkhaykin.com',
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => 'Inspire App Charge',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charge_path
end
end
My routes.rb file has:
resources :charge
Thank you for your help!
回答1:
You should not divert from Rails standards, that will most of the time punish you for it. You should rename your controller back to ChargesController
and take a look at "Singular Resources" on how you can solve your issue.
So the changes that you need to fix your issues are as follows:
- Rename
app/controllers/charge_controller.rb
toapp/controllers/charges_controller.rb
- Rename
class ChargeController
toclass ChargesController
- Replace
resources :charge
withresource :charge
By replaceing resources :charge
with resource :charge
you will be creating a singular charge resource with the path /charge
.
With your current setup i.e. resources :charge
you will see the following (which is not what you want):
charge_index GET /charge(.:format) charge#index
POST /charge(.:format) charge#create
new_charge GET /charge/new(.:format) charge#new
edit_charge GET /charge/:id/edit(.:format) charge#edit
charge GET /charge/:id(.:format) charge#show
PUT /charge/:id(.:format) charge#update
DELETE /charge/:id(.:format) charge#destroy
As you can see above the charge_path
resolves to charge#show
but if you look at the path it also requires an :id
parameter which you are not supplying in your form_tag :charge_path
call.
回答2:
You need to change your controller name to ChargesController
, change the path helper to charges_path
and the routes to resources :charges
.
Also, the form should be POST
ing.
来源:https://stackoverflow.com/questions/20450541/stripe-actioncontrollerurlgenerationerror-no-route-matches-missing-requir