STRIPE ROR: No route matches charges/new error - ruby-on-rails

I am a newbie in ROR,
I am trying to integrate stripe in my ROR project using this link:
https://stripe.com/docs/checkout/rails
I have addded everything as they suggested by when I go to http://localhost:3000/charges/new route, it gives me following error:
No route matches charges/new error
config/routes.rb
Rails.application.routes.draw do
mount API::Root => '/'
# Getting unmatched routes
get '*unmatched_route', to: 'application#raise_not_found'
resources :charges
end
Here are the routes generated:
charges GET /charges(.:format) charges#index
POST /charges(.:format) charges#create
new_charge GET /charges/new(.:format) charges#new
edit_charge GET /charges/:id/edit(.:format) charges#edit
charge GET /charges/:id(.:format) charges#show
PATCH /charges/:id(.:format) charges#update
PUT /charges/:id(.:format) charges#update
DELETE /charges/:id(.:format) charges#destroy
charges_controller.rb:
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#amount = 500
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to 'new_charge_path'
end
end
new.html.erb
<%= 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: $5.00</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="A month's subscription"
data-amount="500"
data-locale="auto"></script>
<% end %>
Can anyone help, what I am missing on? Thanks in advance.

There was a minor mistake in the code of routes file.
The below-mentioned code should be at the last of the routes file. [Refernce] And I had added resources :charges code below that line, that was the reason I was getting above mentioned error.
# Getting unmatched routes
get '*unmatched_route', to: 'application#raise_not_found'
The code started to work when I changed the content of the routes file as:
Rails.application.routes.draw do
mount API::Root => '/'
resources :charges
# Getting unmatched routes
get '*unmatched_route', to: 'application#raise_not_found'
end

Related

Values are nil for form submission (param is missing or the value is empty: amount)

I am a newbie with rails so forgive me. I know I am getting this error because I specified that amount be required for the parameters. If I did not, I end up with a transaction entry with just a transaction_id with every other field being nil. I believe my problem has to deal with my routes, but I'm not sure whats wrong.
My error:
ActionController::ParameterMissing in TransactionsController#create
param is missing or the value is empty: amount
But I can see that the fields are being passed:
Parameters:
{"utf8"=>"✓","authenticity_token"=>
"H+Xxpze7HWC9oduZC2CSxnWHztfhabEMRCoYy0Gw7upNknF2aIHsZ1G/xQOsICTVd7n4btqtT5760UL7QovIrA==",
"transaction"=>{"amount"=>"29", "transactionType"=>"withdraw"}, "commit"=>"Create Transaction"}
My TransactionsController:
class TransactionsController < ApplicationController
def new
#account = Account.find(params[:account_id])
#transaction = Transaction.new
#transaction.account_id = #account.id
end
def create
#transaction = Transaction.new(transactions_params)
if #transaction.save
redirect_to '/viewAccount/:id'
else
render 'new'
end
end
private
def transactions_params
params.require(:amount).permit(:account_id, :transactionType)
end
end
My New View (form):
<div class="destination">
<div class="container">
<div class = "form">
<h3>Add a new transaction for <%= current_user.email %> </h3>
<%= form_for(#transaction) do |f| %>
<%= f.text_field :amount %>
<%= f.select :transactionType, [['withdraw', 'withdraw'], ['deposit', 'deposit']] %>
<%= f.submit "Create Transaction", class: "btn-submit" %>
<% end %>
</div>
</div>
</div>
My routes:
Rails.application.routes.draw do
root 'mysite#index'
get 'signup' => 'users#new'
post 'signup' => 'users#create'
resources :users
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
get'newAccount' => 'accounts#new'
get 'viewAccount/:id' => 'banksite#show'
delete 'logout' => 'sessions#destroy'
get 'transactions' => 'transactions#new'
post 'transactions' => "transactions#create"
resources :transactions
Banking View/start of transactions new
<div class=content>
<div class=main>
<h1>Welcome to Online Banking <%= current_user.email %></h1>
<p>You're only allowed to see this page if you are logged in</p>
<h2><%= current_user.email %> 's Account Summary</h2>
<h3>Balance: $ <%= #account.balance %> </h3>
<%= link_to "Create Transaction",
:controller => "transactions",
:action => "new",
:account_id => #account.id %>
</div>
</div>
</div>
My models:
class User < ActiveRecord::Base
has_secure_password
has_one :account
end
class Account < ActiveRecord::Base
belongs_to :user
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :account
end
I would appreciate any insight into this error.
This:
params.require(:amount).permit(:account_id, :transactionType)
is expecting parameters like:
"amount" => { "account_id" => "...", "transactionType" => "..." }
but your parameters look like:
"transaction"=>{"amount"=>"29", "transactionType"=>"withdraw"}
Also, there is no account_id in your form.
First you'll need to get account_id into your form with something like:
<%= f.hidden_field :account_id %>
Then you need to update your form parsing in your controller with something like:
params.require(:transaction).permit(:account_id, :amount, :transactionType)
so that it will be looking for "transaction" at the top level and "account_id", "amount", and "transactionType" inside that.

current_user.role not changing upon upgrade (Stripe)

My standard current_user.role is not changing to premium within my ChargesController create action, even though my create (post) action follows through. My downgrade action within my UsersController performs properly and changes a users role just find, using the same current_user.role = 'new_role_here' just fine. I'm curious as to why my current_user.role is not changing upon a successful save message? Any help would be appreciated, thanks.
ChargesController Using stripe
before_action :require_sign_in
def new
#stripe_btn_data = {
key: Rails.configuration.stripe[:publishable_key].to_s,
description: "BigMoney Membership - #{current_user.email}",
amount: 10
}
end
def create
#amount = 500
customer = Stripe::Customer.create(
email: current_user.email,
source: params[:stripeToken]
)
charge = Stripe::Charge.create(
customer: customer.id,
amount: #amount,
description: "BigMoney Membership - #{current_user.email}",
currency: 'usd'
)
current_user.role = 'premium'
if current_user.save!
flash[:notice] = "Thanks for all the money, #{current_user.email}! changed to premium member, #{current_user.role}"
redirect_to wikis_path # or wherever
end
# Stripe will send back CardErrors, with friendly messages
# when something goes wrong.
# This `rescue block` catches and displays those errors.
rescue Stripe::CardError => e
flash[:alert] = e.message
redirect_to new_charge_path
end
end
charges/new.html.erb
<%= 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: $5.00</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="A month's subscription"
data-amount="500"
data-locale="auto"></script>
<% end %>
routes
Rails.application.routes.draw do
get 'charges/create'
get "log_in" => 'sessions#new', :as => "log_in"
get "log_out" => 'sessions#destroy', :as => "log_out"
get "sign_up" => "users#new", :as => "sign_up"
get "my_account" => "users#show", :as => "my_account"
get 'users/confirm' => 'users#confirm'
root :to => "sessions#new"
resources :users
resources :sessions
resources :wikis
resources :charges, only: [:new, :create]
I figured out that that if I used current_user.update_attribute(:role, 'premium') instead of current_user.role = 'premium it worked.

partials not displaying on new charges controller (stripe)

I made a new controller to integrate Stripe Checkout, but it's acting as its own entire website and none of my partials (_header, _footer) are displaying.
The current setups is straight from their tutorial https://stripe.com/docs/checkout/guides/rails
Charges Controller
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#amount = 100
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken],
:plan => "tier1",
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
Routes
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
get 'charges' => 'charges#new'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :charges
end
/layouts/charges.html.erb (controller view)
<% provide(:title, 'Edit Billing') %>
<%= yield %>
views/charges/new.html.erb (form with Stripe Checkout on it)
<%= 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: $1.00</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="Tier 1 Monthly Subscription"
data-amount="100"
data-locale="auto"
data-image="images/marketplace.png"
data-name="Pallet Tier 1"
data-description="Tier 1 Monthly Subscription"
data-label="Join" >
</script>
views/charges/create.html.erb (redirect after successful charge)
<% provide(:title, 'Edit Billing') %>
<h2>Thanks, you paid <strong>$1.00</strong>!</h2>

Why do I get NoMethodError in Games#new for my game form but the analog for my Users#new

I am creating a a site in RoR and and I have built the user signup and login forms. Everything works great. The thing is, I went to create another object called games, which functions almost identically to users, but when I try to interact with it I get an error. I built the forms almost exactly the same and the routing I congruent.
Here is my user new.html.erb:
<!DOCTYPE html>
<html>
<body>
<% provide(:title, 'Sign up') %>
<h1 class="heading1" >Sign up</h1>
<br>
<div>
<%= form_for(#user, :html => { :class => 'form' }) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<br>
<%= f.label :email %>
<%= f.text_field :email %>
<br>
<%= f.label :username %>
<%= f.text_field :username %>
<br>
<%= f.label :password %>
<%= f.password_field :password %>
<br>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>
<br>
<br>
<%= f.submit "Create my account", class: "submit" %>
<% end %>
</div>
</div>
</body>
</html>
and my users controller new and create methods:
def create
#user = User.new(user_params)
if #user.save
sign_in #user
redirect_to #user
else
render 'new'
end
end
def new
#user =User.new
end
private
def user_params
params.require(:user).permit(:name, :email, :username, :password,
:password_confirmation)
end
end
and my game new.html.erb:
<!DOCTYPE html>
<html>
<body>
<h1 class="heading1" >Create Game</h1>
<br>
<div>
<%= form_for(#game, :html => { :class => 'form' }) do |i| %>
<%= i.label :title %>
<%= i.text_field :title %>
<br>
<br>
<%= i.submit "Create Game", class: "submit" %>
<% end %>
</div>
</div>
</body>
</html>
and my game controller:
def create
#game = Game.new(game_params)
if #game.save
redirect_to root_url
else
render 'create'
end
end
def new
#game = Game.new
end
private
def game_params
params.require(:game).permit(:title)
end
end
and my routing file:
Rails.application.routes.draw do
resources :sessions, only: [:new, :create, :destroy]
resources :users
match '/new_game', to: 'games#new', via: 'get'
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout', to: 'sessions#destroy', via: 'delete'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'home#home'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
The rails server error page reads:
NoMethodError in Games#new
Showing /Users/Karen/Desktop/BR2/app/views/games/new.html.erb where line #7 raised:
undefined method `games_path' for #<#<Class:0x007fbfd6bdb260>:0x007fbfd6bd8948>
Extracted source (around line #7):
4
5
6
7
8
9
10
<h1 class="heading1" >Create Game</h1>
<br>
<div>
<%= form_for(#game, :html => { :class => 'form' }) do |i| %>
<%= i.label :title %>
<%= i.text_field :title %>
<br>
Rails.root: /Users/Karen/Desktop/BR2
Application Trace | Framework Trace | Full Trace
app/views/games/new.html.erb:7:in `_app_views_games_new_html_erb___3427370169918602482_70230959128880'
Request
Parameters:
None
I really appreciate all and any help. if there is any more information I can provide please say so.
Thank you
The best option is to add games specific RESTful routes in routes.rb
resources :games
and remove match '/new_game', to: 'games#new', via: 'get' route.
Doing this will give you the following Restful routes:
Prefix Verb URI Pattern Controller#Action
games GET /games(.:format) games#index
POST /games(.:format) games#create
new_game GET /games/new(.:format) games#new
edit_game GET /games/:id/edit(.:format) games#edit
game GET /games/:id(.:format) games#show
PATCH /games/:id(.:format) games#update
PUT /games/:id(.:format) games#update
DELETE /games/:id(.:format) games#destroy
So upon form submission your application would route to create action (games_path) by HTTP Post request.
Currently you have just defined a single route for games resource which routes to new action with
match '/new_game', to: 'games#new', via: 'get'
But there is no route for create action which is why you receive the error as undefined method 'games_path' on the form
If you don't wish to use the RESTful routes(resources :games) then you would have to define a route as:
match '/games', as: 'games', to: 'games#create', via: 'post'
for create action.
You will find that when you do bundle exec rake routes in your console, you have not actually created named routes for your games paths.
If you're using match and you want to name a route (so you have something like games_path available), you'd have to do this:
match `/games`, as: 'games', to: 'games#index', via: :get
A much easier way is to use resources for most of your routes, and just go with the default RESTFUL paths:
resources :games
# Now you have access to '/games/new', '/games/:id',
# '/games', etc, as well as names such as `games_path`.
# Check `bundle exec rake routes` for all of them.
See Rails Routing for more information

rails 3 validations not allowing form submission

I have a problem with validations in rails 3. I have got a model where i am simply trying to validate one of the field of the model form, that is that it should not be blank. But the problem is even though I have filled that text field still it shows the error. What could be the possible problems?
MODEL FILE:
class Page < ActiveRecord::Base
validates :title, :presence => true
end
_form.html.erb
<%= form_for(#page) do |f| %>
<% if #page.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#page.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #page.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.label :author %><br />
<%= f.text_field :author %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :reference %><br />
<%= f.select(:reference,[['google',1],['yahoo',2],['MSN',3],['Ask',4]]) %>
</p>
<%= f.submit "Submit" %>
<% end %>
And here is my controller file:
class PagesController < ApplicationController
def index
#total = Page.count
#pages = Page.find(:all)
end
def new
#page = Page.new
end
def create
#page = Page.new(params[:pages])
if #page.save
redirect_to pages_path, :notice => "The data has been saved!"
else
render "new"
end
end
def edit
#page = Page.find(params[:id])
if request.post?
#page.title = params[:title]
#page.author = params[:author]
#page.email = params[:email]
#page.body = params[:body]
#page.reference = params[:reference]
#page.save
redirect_to :action => 'index'
end
end
def destroy
#page = Page.find(params[:id])
#page.destroy
redirect_to :action => 'index'
end
end
My routes.rb is as follows:
Rorapp::Application.routes.draw do
get "home/index"
post "home/search"
get "home/_help"
get "home/create"
get "pages/index"
get "pages/new"
post "pages/new"
post "pages/edit"
get "pages/edit"
resources :pages
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => 'home#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
match ':controller(/:action(/:id(.:format)))'
end
You have duplicate routes.
Try replacing your routes.rb file with the following:
routes.rb
Rorapp::Application.routes.draw do
get "home/index"
post "home/search"
get "home/_help"
get "home/create"
resources :pages
root :to => 'home#index'
match ':controller(/:action(/:id(.:format)))'
end
Also you could create the update method in your PagesController, so your CRUD will be complete.
The create method in your controller refers to param[:pages]. Should this be param[:page]?

Resources