I'm getting an ActiveRecord::RecordNotFound in PaymentsController#create error / Couldn't find Product without an ID
I'm trying to set up Stripe payments, but I get an error after the credit card is submitted. I'm doing this for an Intro to Rails class, and my classmates have the same code but theirs' is working.
It appears that the error is in this line:
@product = Product.find(params[:product_id])
Here is my Payments Controller:
class PaymentsController < ApplicationController
def new
@product = @product.payments.new
end
def create
token = params[:stripeToken]
@product = Product.find(params[:product_id])
@user = current_user
# Create the charge on Stripe's servers - this will charge the user's card
begin
charge = Stripe::Charge.create(
amount: (@product.price*100), # amount in cents, again
currency: "usd",
source: token,
description: params[:stripeEmail]
)
if charge.paid
Order.create(
product_id: @product.id,
user_id: @user.id,
total: @product.price
)
#flash[:success] = "You have successfully paid for your order!"
UserMailer.order_confirmation_email(@user, @product).deliver_now
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 product_path(@product), notice: "Thank you for your purchase."
end
end
Here is the console message:
Started POST "/payments/create" for 127.0.0.1 at 2018-12-10 10:49:15 -0500
Processing by PaymentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jJhGPS9Su0IuepHt2Eea/hCEhDo3A3fggu6EUjwLDrJphrC8VmNRycUqzyLGiJpcaN3mHOzr224BYsbgbjo38Q==", "stripeToken"=>"tok_1Dfr0PHrTxlTJx3aoOtOh2Z9", "stripeTokenType"=>"card", "stripeEmail"=>"myemail@gmail.com"}
Completed 404 Not Found in 2ms (ActiveRecord: 0.0ms)
routes.rb
Rails.application.routes.draw do
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout' }
resources :users
resources :products, :invoices, :orders, :users # 5.1 added ", :invoices, :orders, :users"
resources :users, except: [:index]
get 'simple_pages/about'
get 'simple_pages/contact'
get 'simple_pages/index'
get 'simple_pages/landing_page'
post 'simple_pages/thank_you'
post 'payments/create'
root 'simple_pages#landing_page'
mount ActionCable.server => '/cable'
resources :products do # 5.8 added
resources :comments
end
resources :products do
resources :payments
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
payments/_form.html.erb
<%= form_for [@product, @payment] do |f| %>