i create a simple banking app This is the Link For study purpose. alll the function are work charming but i weant to check validation if user enter Negative value like -100 so it shows error or alert message. so how can ii implement.
Thanks in advance :)
_form.html.erb
<%= form_for(#depositemoney) do |f| %>
<% if #depositemoney.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#depositemoney.errors.count, "error") %> prohibited this depositemoney from being saved:</h2>
<ul>
<% #depositemoney.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :balance %><br>
<%= f.number_field :balance %>
</div>
<%= f.hidden_field :u_id, :value => current_user.id %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Model.rb
class Depositemoney < ActiveRecord::Base
# validates :balance, :numericality => {:only_integer => true}
# validates :balance, presence: true
validates :balance, presence: true
# validates :balance, :inclusion => {:in => [1,2]}
validates :balance, format: { with: /\A\d+\z/, message: "Integer only. No sign allowed." }
end
I tried 3 Types of validations but it does not worrk for me so any one can help me out :)
:greater_than or :greater_than_or_equal_to option is that.
class Hoge < ApplicationRecord
validates :balance, numericality: { greater_than: 0 }
end
it works like below:
Loading development environment (Rails 5.1.4)
[1] pry(main)> Hoge.create(balance: 1)
(0.6ms) SET NAMES utf8mb4 COLLATE utf8mb4_general_ci, ##SESSION.sql_mode = CONCAT(CONCAT(##sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), ##SESSION.sql_auto_is_null = 0, ##SESSION.wait_timeout = 2147483
(0.1ms) BEGIN
SQL (12.2ms) INSERT INTO `hoges` (`balance`, `created_at`, `updated_at`) VALUES (1, '2017-10-18 06:06:18', '2017-10-18 06:06:18')
(11.1ms) COMMIT
[2] pry(main)> Hoge.create(balance: -1)
(0.2ms) BEGIN
(0.2ms) ROLLBACK
=> #<Hoge:0x007fa212e1cd80 id: nil, balance: -1, created_at: nil, updated_at: nil>
[4] pry(main)> Hoge.create(balance: -1).errors
(0.3ms) BEGIN
(0.2ms) ROLLBACK
=> #<ActiveModel::Errors:0x007fa20fcc37c0
#base=#<Hoge:0x007fa20f6c08f0 id: nil, balance: -1, created_at: nil, updated_at: nil>,
#details={:balance=>[{:error=>:greater_than, :value=>-1, :count=>0}]},
#messages={:balance=>["must be greater than 0"]}>
FYI: http://guides.rubyonrails.org/active_record_validations.html
Related
This is a continuation from here:
Passing a form as a local to a ajax rendered partial in Rails 5
I've looked all over and can't find a solution that works.
Relevant Controller (profits_controller.rb):
def new_tabs
#market = Market.order('mjsnumber').all.first
#profit = Profit.new
profit_types_markets_products
end
def fetch_market
#market = Market.where(:id => params[:market_id]).first
#form = params["form"]
respond_to do |format|
format.js { render layout: false}
end
end
Relevant View (new_tabs.html.erb):
<%= simple_form_for #profit, :remote => true do |form| %>
<% #markets.each_with_index do |market, i| %>
<%= link_to market.nick, fetch_market_path(:market_id => market.id, :form => form, profit: #profit), :remote=>'true', :id => 'navBtn' + market.id.to_s, :class => 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
<% end %>
<%= render :partial => 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } %>
Relevant Partial (_edit_partial_form.html.erb):
<%= market.namae %>
<%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
<%= figures_form.input "[test]" %>
<% end %>
Relevant JS (fetch_market.js.erb):
$("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: #form, profit: #profit } ) %>");
Routes:
resources :profits do
resources :markets
resources :products
collection do
get 'new_by_product_type'
get 'new_tabs'
end
end
get "/fetch_market" => 'profits#fetch_market', as: 'fetch_market'
patch 'profits/:id/autosave', as: :autosave_profit, to: 'profits#autosave'
It renders the partial fine, and the links appear to contain the FormBuilder information. When I click the link and add a "puts params" to the controller, it shows the params there. But then gives me an error when loading the partial in console:
ActionView::Template::Error (undefined local variable or method `form' for #<#<Class:0x00007fdbd6453648>:0x00007fdbd68db5f8>
Did you mean? fork):
1: $("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Full Error from local environment when I click on the link for the second market in the list of generated markets:
Processing by ProfitsController#fetch_market as JS
Parameters: {"form"=>"#<SimpleForm::FormBuilder:0x00007fed50dba9f8>", "market_id"=>"2"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /home/mudl/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Market Load (0.3ms) SELECT "markets".* FROM "markets" WHERE "markets"."id" = $1 ORDER BY "markets"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/controllers/profits_controller.rb:75
Rendering profits/fetch_market.js.erb
Rendered profits/_edit_partial_form.html.erb (6.5ms)
Rendered profits/fetch_market.js.erb (7.5ms)
Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.6ms)
ActionView::Template::Error (undefined method `simple_fields_for' for "#<SimpleForm::FormBuilder:0x00007fed50dba9f8>":String):
11: MJS 番後: <%= market.mjsnumber %>
12: </span>
13: </div>
14: <%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
15: <%= figures_form.input "[test]" %>
16: <% end %>
17:
app/views/profits/_edit_partial_form.html.erb:14:in `_app_views_profits__edit_partial_form_html_erb__249336059151108365_70328546926840'
app/views/profits/fetch_market.js.erb:1:in `_app_views_profits_fetch_market_js_erb___2023159631102932010_70328546933900'
app/controllers/profits_controller.rb:78:in `block (2 levels) in fetch_market'
app/controllers/profits_controller.rb:77:in `fetch_market'
(undefined method `simple_fields_for' for "#<SimpleForm::FormBuilder
I am removing the simple_form tag because after a simple test changing the simple_form to a regular form, the error persists with whatever method I call after field_for in the partial.
Thanks in advance.
EDIT:
So I ended up giving up and just using the #profit variable to make a new form in the partial (not ideal, but I'll hack it). Still curious if this is even possible, though, so I'll leave the question open..
So first of all you need to close your form block, then if you couldn`t pass form to partial then try to do this without partial
<%= simple_form_for #profit, remote: true do |form| %>
<% #markets.each_with_index do |market, i| %>
<%= link_to market.nick, fetch_market_path(market_id: market.id, form: form, profit: #profit), id: 'navBtn' + market.id.to_s, class: 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
<%= market.name %>
<% end %>
<%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
<%= figures_form.input "[test]" %>
<% end %>
<% end %>
And better to used something_key: "value" instead of this syntax :something_key => "value"
So I've recently implemented a phone/sim checker. The first form input requires the user to input their phone number. If the phone number exists in the database, render the phone number found message, otherwise replace the phone number form with the sim number form. Again if the sim number exists in the database, render the sim number found message, otherwise render the sim number not found message.
Is anybody able to show me an example on how I can use jquery validation on the user's input before the checkphone / checksim method is fired when the users clicks submit? Validations have been setup in my phone model (phone.rb)
Code below:
app/controllers/phones_controller.rb
class PhonesController < ApplicationController
def checkphone
#phone_number = Phone.where(phone_number: params[:phone][:phone_number])
respond_to do |format|
if #phone_number.exists?
format.js {render 'phone-found'}
elsif #phone_number.blank?
format.js {render 'phone-not-found'}
else
format.js {render 'errors'}
end
end
end
def checksim
#sim_number = Phone.where('sim_number = ?', params[:sim][:sim_number])
respond_to do |format|
if #sim_number.exists?
format.js {render 'sim-found'}
elsif #sim_number.blank?
format.js {render 'sim-not-found'}
else
format.js {render 'errors'}
end
end
end
private
def phone_params
params.require(:phone).permit(
:phone_number
)
end
def sim_params
params.require(:sim).permit(
:sim_number
)
end
end
app/models/phone.rb
class Phone < ActiveRecord::Base
validates :phone_number, length: {minimum: 11, maximum: 11}, allow_blank: false
validates :sim_number, length: {minimum: 12, maximum: 12}, allow_blank: false
end
app/views/phones/index.html.erb
<div id="phone-number-found"></div>
<div id="phone-number-not-found"></div>
<div id="error"></div>
<%= form_for :phone, :url => url_for(:action => 'checkphone', :controller => 'phones'), remote: true, html: { id: 'phone-number-form'} do |f| %>
<%= f.label "Phone Number:" %>
<%= f.number_field :phone_number %>
<%= submit_tag("Check") %>
<% end %>
app/views/phones/phone-found.js.erb
$('#phone-number-found').html('Phone Number Found!');
$('#phone-number-not-found').html('');
$('#error').html('');
$('#phone-number-form').hide();
app/views/phones/phone-not-found.js.erb
$('#phone-number-found').append("<%= j render(partial: 'sim') %>")
$('#phone-number-not-found').html('Phone Number Not Found!');
$('#error').html('');
$('#phone-number-form').hide();
app/views/phones/_sim.html.erb
<div id="sim-number-found"></div>
<div id="sim-number-not-found"></div>
<div id="error"></div>
<%= form_for :sim, :url => url_for(:action => 'checksim', :controller => 'phones'), remote: true, html: { id: 'sim-number-form'} do |f| %>
<%= f.label "Sim Number:" %>
<%= f.number_field :sim_number %>
<%= submit_tag("Check") %>
<% end %>
app/views/phones/sim-found.js.erb
$('#phone-number-found').html('Sim Found')
$('#phone-number-not-found').html('');
$('#phone-number-error').html('');
app/views/phones/sim-not-found.js.erb
$('#phone-number-found').html('');
$('#phone-number-not-found').html('Sim Number Not Found!');
$('#error').html('');
app/views/phones/errors.js.erb
$('#phone-number-found').html('');
$('#phone-number-not-found').html('');
$('#error').html('Error!');
config/routes.rb
post "/checkphone" => "phones#checkphone"
post "/checksim" => "phones#checksim"
resources :phones, path: '4g-promo'
Would be greatly appreciated if someone could show me how I can apply jquery validation according to my model validation rules before checkphone and checksim methods fires. Thanks!
Adding minlength, maxlength and required should do the trick. Then the sim partial will look thus:
app/views/phones/_sim.html.erb
<div id="sim-number-found"></div>
<div id="sim-number-not-found"></div>
<div id="error"></div>
<%= form_for :sim, :url => url_for(:action => 'checksim', :controller => 'phones'), remote: true, html: { id: 'sim-number-form'} do |f| %>
<%= f.label "Sim Number:" %>
<%= f.number_field :sim_number, minlength: 12, maxlength: 12, required: true %>
<%= submit_tag("Check") %>
<% end %>
User gem 'client_side_validations' that will use your server side validation for client side as well.
I am encountering a minor problem with some javascripts/AJAX and i was hoping someone can help me or point me to the right direction.
What I am trying to do is to populate my per-carton-price-field using collection_select in the same form. This is an order form which is suppose to create an entry into my order table. Form view as below:
new.html.erb
<h1>Add a new order for <%= #customer.name %></h1>
<div class="row">
<%= form_for(#order) do |f| %>
<div class="col-md-6">
<%= render 'shared/error_messages', object: f.object %>
<%= f.hidden_field :customer_id, :value => #customer.id %>
<h3>Order Details</h3>
<%= f.label :address_id, "Delivery Address" %>
<%= f.collection_select :address_id, #addresses, :id, :select_address, :prompt => "Select delivery location",class: 'form-control' %></br>
<%= f.label :remark, "Order Remark" %>
<%= f.text_area :remark, class: 'form-control' %></br>
<h3>What items would you like to place?</h3>
<%= f.add_nested_fields_link :single_orders, "Add Product" %>
<%= f.nested_fields_for :single_orders do |builder| %>
<%= builder.collection_select :product_id, #products, :id, :select_product, {:prompt => "choose product"}, {:class => "product_selection form-control"} %>
<%= builder.text_field :ctn_price, placeholder: "Price/carton", id: "price", class: 'ctn_price_field form-control' %>
<%= builder.text_field :qty, placeholder: "Quantity",id: "quantity", class: 'form-control' %>
<%= builder.text_field :price, placeholder: "Amount", id: "total-amount", readonly: true, class: 'form-control' %>
<%= builder.remove_nested_fields_link %>
<% end %>
</div>
<%= f.submit "place order", class: "btn btn-primary" %>
<% end %>
</div>
I would like the collection_select:product_id to pull out all the products in the products table. When the user selects whichever product they want to order from the dropdown, the price for the selected product will populate the text_field:ctn_price.
product.rb
class Product < ActiveRecord::Base
has_many :special_prices, dependent: :destroy
has_many :single_orders
has_many :package_orders_products
before_save :upcase_stock_code
validates :name, presence: true, length: { maximum: 50 }
validates :stock_code, presence: true, length: { maximum: 20 }
validates :status, presence: true, length: { maximum: 10 }
validates :price, presence: true
private
def select_product
"#{name} - #{price}"
end
# Converts stock_code to all upper-case.
def upcase_stock_code
self.stock_code = stock_code.upcase
end
end
single_order.rb
class SingleOrder < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order, presence: true
validates :product_id, presence: true
validates :qty, presence: true
validates :price, presence: true
validates :ctn_price, presence: true
end
Any help is appreciated as I have been stuck for days :(
Thanks for any help in advance.
You can do this using ajax call. Before that create a api to take product_id as input and render #product as output.
$("#product_selection_id").on('change', function(){
var product_id = $(this).val();
$.ajax({
method: "GET",
type: 'html',
url: "call_url_for_get_product_api_with_product_id",
cache: false,
success: function(data, textStatus, jqxhr) {
console.log("success");
}
});
});
Suppose your url_for_get_product_api goes to get_product action as a js request. so create a template with get_product.js.erb as follows
$('#ctn_price_field').val(#product.price)
#ihave not tested this code change this according to your requirements.
Note: Here i have given a pattern impliment this by your own. Thanks.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Rails - AJAX to for new/create action
I have a timeline that has partials for events on it, so you can CRUD events directly on the timeline. I've got the delete part working fine, so that the delete partial and the timeline refresh each time an event gets deleted. However, I can't get it working when a new event is created. Instead of refreshing the form and the timeline, the whole page refreshes.
I'm assuming this is something to do with the controller? But I can't seem to fix it. Any help would be much appreciated, thanks :0)
events controller:
def create
#event = Event.new(params[:event])
respond_to do |format|
if #event.save
format.html { redirect_to #event.timeline, notice: 'Event was successfully created.' }
format.json { render json: #event, status: :created, location: #event }
format.js
else
format.html { render action: "new" }
format.json { render json: #event.errors, status: :unprocessable_entity }
format.js
end
end
end
timeline/show:
<div id="new-event">
<%= render :partial => "new_event", :locals => { :event => Event.new(:timeline_id=>#timeline.id) }, :remote => true %>
</div>
timeline/_new_event:
<br />
<h2>Add an event</h2>
<h4>Fill in the form and click 'Create Event' to add a new event to the timeline.</h4>
<%= form_for(event) do |f| %>
<% if event.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(event.errors.count, "error") %> prohibited this event from being saved:</h2>
<ul>
<% event.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%=f.hidden_field 'timeline_id', :value => current_user.timeline.id %>
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :start_date, :order => [:day, :month, :year], :start_year => 1800 %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :headline, :size => 50 %>
</div>
<div class="field">
<%= f.label :event_description %><br />
<%= f.text_area :text, :size => "47x4" %>
</div>
<%= check_box_tag "blockCheck", :value => "1", :checked => false %>
<div class="field" id="media_box">
<%= f.label :media %> <span>Please paste a URL here</span><br />
<%= f.text_field :media, :size => 50 %>
</div>
<div class="field">
<%= f.label :media_description %><br />
<%= f.text_area :caption, :size => "47x3" %>
</div>
<div class="actions">
<%= f.submit 'Create Event', :class => "btn btn-success", :remote => true %>
</div>
<% end %>
events/create.js.erb:
$('#new-event').html('<%= escape_javascript( render :partial => "/timelines/new_event", :locals => { :event => Event.new(:timeline_id=>#timeline.id) } ) %>');
$('.notice').html("<p>Event was successfully created.</p>");
$('.notice').show(300);
$('#my-timeline-box').html('<%= escape_javascript( render :partial => "/timelines/my_timeline" ) %>');
$('#show-timeline').html('<%= escape_javascript( render :partial => "/timelines/show_timeline" ) %>');
(The bottom two lines are to refresh the timeline iteself).
UPDATE:
Here is the error message:
Started POST "/events" for 127.0.0.1 at 2012-10-16 14:52:37 +0100
Processing by EventsController#create as JS
Parameters: {"utf8"=>"V", "authenticity_token"=>"i8oiRI7rOLsfb5o45QCK0te/hAsWv
BMTqpxU9KrbmNA=", "event"=>{"timeline_id"=>"1", "start_date(3i)"=>"16", "start_d
ate(2i)"=>"10", "start_date(1i)"=>"2012", "headline"=>"", "text"=>"", "media"=>"
", "caption"=>""}, "commit"=>"Create Event"}
←[1m←[35m (0.0ms)←[0m begin transaction
←[1m←[36mSQL (5.0ms)←[0m ←[1mINSERT INTO "events" ("caption", "created_at", "
credit", "end_date", "headline", "media", "start_date", "text", "thumbnail", "ti
meline_id", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)←[0m [["capti
on", ""], ["created_at", Tue, 16 Oct 2012 13:52:37 UTC +00:00], ["credit", nil],
["end_date", nil], ["headline", ""], ["media", ""], ["start_date", Tue, 16 Oct
2012], ["text", ""], ["thumbnail", nil], ["timeline_id", 1], ["updated_at", Tue,
16 Oct 2012 13:52:37 UTC +00:00]]
←[1m←[35m (88.0ms)←[0m commit transaction
Rendered events/create.js.erb (99.0ms)
Completed 500 Internal Server Error in 617ms
ActionView::Template::Error (Called id for nil, which would mistakenly be 4 -- i
f you really wanted the id of nil, use object_id):
1: $('#new-event').html('<%= escape_javascript( render :partial => "/timelin
es/new_event", :locals => { :event => Event.new(:timeline_id=>#timeline.id) } )
%>');
2: $('.notice').html("<p>Event was successfully created.</p>");
3: $('.notice').show(300);
4: $('#my-timeline-box').html('<%= escape_javascript( render :partial => "/t
imelines/my_timeline" ) %>');
app/views/events/create.js.erb:1:in `_app_views_events_create_js_erb___8626901
43_20024148'
app/controllers/events_controller.rb:59:in `create'
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.4.rc1/lib/action_d
ispatch/middleware/templates/rescues/_trace.erb (5.0ms)
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.4.rc1/lib/action_d
ispatch/middleware/templates/rescues/_request_and_response.erb (2.0ms)
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.4.rc1/lib/action_d
ispatch/middleware/templates/rescues/template_error.erb within rescues/layout (1
000.1ms)
You have :remote => true on the submit button. That's incorrect. It should be on the form:
<%= form_for(event, :remote => true) do |f| %>
You have not initialized #timeline in your controller code. Thus you get a nil action.
So, put in your Create code:
#timeline = current_user.timeline
I'm building a Rails app that takes credit cards and I'm trying to use Stripe to do it. I'm having some issues passing the data from my app to Stripe in order to charge. That's what I'm hoping to get help with on this topic.
First, I have a standard form (with values instead of placeholders for quick submitting for testing purposes). The form successfully enters the name and email into the DB and the customer's "plan" is hardcoded in the controller for the time being:
<%= form_for #customer do |f| %>
<div class="payment-errors"></div>
<div class="name field">
<%= f.label :name %>
<%= f.text_field :name, :value => "Your name" %>
</div>
<div class="email field">
<%= f.label :email %>
<%= f.text_field :email, :value => "yourname#example.com" %>
</div>
<div class="cc_number field">
<%= label_tag 'cc_number' %>
<%= text_field_tag 'cc_number', nil, :value => "4242424242424242" %>
</div>
<div class="ccv field">
<%= label_tag 'ccv' %>
<%= text_field_tag 'ccv', nil, :value => "123" %>
</div>
<div class="cc_expiration field">
<%= label_tag 'cc_month', "Expiration date" %>
<%= text_field_tag 'cc_month', nil, :value => "12" %>
<%= text_field_tag 'cc_year', nil, :value => "2012" %>
</div>
<div class="actions">
<%= f.submit "Continue", :class => 'btn' %>
</div>
<% end %>
Also in my signups_view where the above code is, I have this JS, mostly provided by Stripe:
<script type="text/javascript">
// this identifies your website in the createToken call below
Stripe.setPublishableKey('<%= STRIPE['public'] %>');
function stripeResponseHandler(status, response) {
if (response.error) {
// show the errors on the form
$(".payment-errors").text(response.error.message);
$("input[type=submit]").removeAttr("disabled");
} else {
var form$ = $("form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='customer[stripe_token]' id='stripeToken' value='" + token + "'/>");
// and submit
$('.cc_number.field, .ccv.field, .cc_expiration.field').remove();
form$.get(0).submit();
}
}
$(document).ready(function() {
$("form").submit(function(event) {
// disable the submit button to prevent repeated clicks
$('input[type=submit]').attr("disabled", "disabled");
Stripe.createToken({
number: $('#cc_number').val(),
cvc: $('#ccv').val(),
exp_month: $('#cc_month').val(),
exp_year: $('#cc_year').val()
}, stripeResponseHandler);
// prevent the form from submitting with the default action
return false;
});
});
</script>
There seems to be a problem with the line form$.append("<input type='hidden' name='customer[stripe_token]' id='stripeToken' value='" + token + "'/>");, as my Ruby app breaks when it gets to customer[stripe_token].
Finally, in my `customers_controller`, I have:
def create
#customer = Customer.new(params[:customer])
#customer.product =
if #customer.save
save_order
redirect_to #customer
else
render action: 'new'
end
def save_order
Stripe.api_key = STRIPE['secret']
charge = Stripe::Charge.create(
:amount => 20,
:currency => "usd",
:card => #customer.stripe_token,
:description => "Product 1"
)
end
Whenever I submit the form, it hits the else clause in the controller each time and after plenty of debugging, Googling around and stripping out this from and rebuilding from scratch, I'm still stumped.
Any help would be very very much appreciated.
Edit: Added the customer model
attr_accessible :name, :email, :stripe_token, :product
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:length => { :minimum => 6, :maximum => 60 },
:uniqueness => { :case_sensitive => false }
validates :name, :length => {:minimum => 2, :maximum => 80 }
It would help to see your Customer model to get an idea of what's going on. If #customer.save returns false, it means that a validator is likely failing.
Also, do you have stripe_token as an accessible attribute on your model? Otherwise you won't be able to assign it form the form like you're doing. Note that the token should not be stored in the database, since it can only be used once.
class Customer
attr_accessor :stripe_token # do you have this?
end
One more note: you will probably want to store a Stripe ID field so that you can retrieve customer payments and cancel their account later.