Twilio Rails Integration for Devise and Milia - ruby-on-rails

Firstly sorry for a newbie question. Just started developing in rails around 15 days back. Now I have installed Milia, Devise and they handle all the work for signing up, logging in, and entering the customer data into the DB.
What am I trying to achieve?
I want to send an SMS to a customer, whose mobile no, we will be taking using a data entry form, whose code I have shown below.
Now once all the information is entered, and the create customer button is pressed, all the information is entered into the DB. Once the button is pressed, I want an SMS to be sent via Twilio, to the customer with a defined body.
For this, I have created a controller, an SMS.rb file and a form which has the code which should help in firing the SMS.
FORM for Entering the Information:
<%= form_for [#sms, #tenant, #customer], :html => { :class => "form-horizontal customer" }, :id => 'form1' do |f| %>
<% if #customer.errors.any? %>
<div id="error_expl" class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><%= pluralize(#customer.errors.count, "error") %> prohibited this customer from being saved:</h3>
</div>
<div class="panel-body">
<ul>
<% #customer.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<h3 align=centre>Personal Infomation</h3>
<div class="form-group">
<%= f.label :name, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :name, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :date_of_birth, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :dob, :class => 'form-control datepicker' %>
</div>
</div>
<div class="form-group">
<%= f.label :mobileno, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :mobileno, :class => 'form-control', :id =>"mobileno", onblur:"Calculate()" %>
</div>
</div>
<div class="form-group">
<%= f.label :email_Id, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :emailid, :class => 'form-control' %>
</div>
</div>
<H3 align=centre>Address</H3>
<div class="form-group">
<%= f.label :building, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :building, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :sub_area, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :subarea, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :locality, :class => 'control-label col-md-2'%>
<div class="col-lg-10">
<%= f.text_field :locality, :class => 'form-control', :id => "locality", onblur: "Calculate()" %>
</div>
</div>
<div class="form-group">
<%= f.label :pincode, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :pin, :class => 'form-control' %>
</div>
</div>
<h3 align=left>Medical Information</h3>
<div class="form-group">
<%= f.label :blood_group, :class => 'control-label col-lg-2' %>
<div class="col-lg-10">
<%= f.text_field :bg, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :diseases, :class => 'control-label col-lg-2' %>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'Diabetes', checked('Diabetes'), id: 'diseases_diabetes'%>
<%= label_tag 'diseases_diabetes', 'Diabetes' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'Cancer', checked('Cancer'), id: 'diseases_cancer'%>
<%= label_tag 'diseases_cancer', 'Cancer' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'TB', checked('TB'), id: 'diseases_tb'%>
<%= label_tag 'diseases_tb', 'TB' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'BP', checked('BP'), id: 'diseases_tb'%>
<%= label_tag 'diseases_bp', 'BP' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'HIV', checked('TB'), id: 'diseases_tb'%>
<%= label_tag 'diseases_hiv', 'HIV' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'Brain Tumor', checked('Brain Tumor'), id: 'diseases_tb'%>
<%= label_tag 'diseases_brain_tumor', 'Brain Tumor' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'STD', checked('STD'), id: 'diseases_tb'%>
<%= label_tag 'diseases_std', 'STD' %>
</div>
</div>
<div class="form-group">
<%= f.label :medicine, :class => 'control-label col-md-2 col-sm-3 col-xs-4' %>
<div class="col-lg-10">
<%= f.text_field :medicin, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :allergy, :class => 'control-label col-md-2 col-sm-3 col-xs-4' %>
<div class="col-lg-10">
<%= f.text_field :allergy, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :uid, :class => 'control-label col-md-2 col-sm-3 col-xs-4'%>
<div class="col-lg-10">
<%= f.text_field :uid , :class => 'form-control', :id => 'uid' %>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<br>
<%= f.hidden_field :tenant_id, value: params[:tenant_id], :class => 'form-control' %>
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
root_path, :class => 'btn btn-default' %>
</div>
</div>
<% end %>
SMS.rb FILE:
class SMS < ActiveRecord::Base
def client
Twilio::REST::Client.new Rails.application.secrets.twilio_account_sid, Rails.application.secrets.twilio_token
end
acct_sid = "ACCOUNT_SID"
auth_token = "AUTH_TOKEN"
twilio_no = "+16xxxxxxxxx"
acct_sid = ENV['twilio_account_sid']
auth_token = ENV['twilio_token']
twilio_no = ENV['twilio_no']
def send
numberto = params[:mobileno]
client.account.messages.create(
:messaging_service_sid => Rails.application.secrets.twilio_messaging_service_sid,
:from => "+1xxxxxxxxxx",
:to => "#{numberto}",
:body => "Hi. Thanks a lot for signing up with us. Your UID is: #{uid}"
)
end
The problem I am facing:
I cannot add #sms to the form as it has [#tenant, #cusotmer] already. Adding #sms, gives me an error.
I am frantically stuck and don't know how to proceed. Can you guys help me out?
Things to Know
1. Using Rails 4.2.6
2. Using Ruby 2.3.3
UPDATES
I have updated the Form.html.erb file now.
Here it is:
<%= form_for [#tenant, #customer], :html => { :class => "form-horizontal customer" }, :id => 'form1' do |f| %>
<% if #customer.errors.any? %>
<div id="error_expl" class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><%= pluralize(#customer.errors.count, "error") %> prohibited this customer from being saved:</h3>
</div>
<div class="panel-body">
<ul>
<% #customer.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<h3 align=centre>Personal Infomation</h3>
<div class="form-group">
<%= f.label :name, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :name, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :date_of_birth, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :dob, :class => 'form-control datepicker' %>
</div>
</div>
<div class="form-group">
<%= f.label :mobileno, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :mobileno, :class => 'form-control', value: params[:mobile], :id =>"mobileno", onblur:"Calculate()" %>
</div>
</div>
<div class="form-group">
<%= f.label :email_Id, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :emailid, :class => 'form-control' %>
</div>
</div>
<H3 align=centre>Address</H3>
<div class="form-group">
<%= f.label :building, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :building, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :sub_area, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :subarea, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :locality, :class => 'control-label col-md-2'%>
<div class="col-lg-10">
<%= f.text_field :locality, :class => 'form-control', :id => "locality", onblur: "Calculate()" %>
</div>
</div>
<div class="form-group">
<%= f.label :pincode, :class => 'control-label col-md-2' %>
<div class="col-lg-10">
<%= f.text_field :pin, :class => 'form-control' %>
</div>
</div>
<h3 align=left>Medical Information</h3>
<div class="form-group">
<%= f.label :blood_group, :class => 'control-label col-lg-2' %>
<div class="col-lg-10">
<%= f.text_field :bg, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :diseases, :class => 'control-label col-lg-2' %>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'Diabetes', checked('Diabetes'), id: 'diseases_diabetes'%>
<%= label_tag 'diseases_diabetes', 'Diabetes' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'Cancer', checked('Cancer'), id: 'diseases_cancer'%>
<%= label_tag 'diseases_cancer', 'Cancer' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'TB', checked('TB'), id: 'diseases_tb'%>
<%= label_tag 'diseases_tb', 'TB' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'BP', checked('BP'), id: 'diseases_tb'%>
<%= label_tag 'diseases_bp', 'BP' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'HIV', checked('TB'), id: 'diseases_tb'%>
<%= label_tag 'diseases_hiv', 'HIV' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'Brain Tumor', checked('Brain Tumor'), id: 'diseases_tb'%>
<%= label_tag 'diseases_brain_tumor', 'Brain Tumor' %>
</div>
<div class="col-md-2 col-sm-3 col-xs-4">
<%= check_box_tag 'customer[diseases][]', 'STD', checked('STD'), id: 'diseases_tb'%>
<%= label_tag 'diseases_std', 'STD' %>
</div>
</div>
<div class="form-group">
<%= f.label :medicine, :class => 'control-label col-md-2 col-sm-3 col-xs-4' %>
<div class="col-lg-10">
<%= f.text_field :medicin, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :allergy, :class => 'control-label col-md-2 col-sm-3 col-xs-4' %>
<div class="col-lg-10">
<%= f.text_field :allergy, :class => 'form-control' %>
</div>
</div>
<div class="form-group">
<%= f.label :uid, :class => 'control-label col-md-2 col-sm-3 col-xs-4'%>
<div class="col-lg-10">
<%= f.text_field :uid , :class => 'form-control', :id => 'uid' %>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<br>
<%= f.hidden_field :tenant_id, value: params[:tenant_id], :class => 'form-control' %>
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
root_path, :class => 'btn btn-default' %>
</div>
</div>
<% end %>
I have also updated the Customer.rb file:
Here it is:
def format_phone_number
self.to = "+91" + (self.to.gsub('-',''))
end
def client
Twilio::REST::Client.new Rails.application.secrets.twilio_account_sid, Rails.application.secrets.twilio_token
end
acct_sid = "Axxxxxxxxxxxx"
auth_token = "6xxxxxxxxxxx"
twilio_no = "+1xxxxxxxxxxx"
acct_sid = ENV['twilio_account_sid']
auth_token = ENV['twilio_token']
twilio_no = ENV['twilio_no']
def send (to,body)
client.account.messages.create(
:messaging_service_sid => Rails.application.secrets.twilio_messaging_service_sid,
:to => '#{mobileno}',
:body => "Hi. Thanks a lot for signing up with us. Your UID is: #{uid}"
)
end
Instead of writing in the sms.rb file, I have written the code in customer.rb and erased the sms.rb file and now it is connecting well to the Twilio API. But it takes a random number as the to number +66245366 and so the message sending fails. I don't know why this is happening.
Latest Updated
Customer.rb
class Customer < ActiveRecord::Base
before_save do
self.diseases.gsub!(/[\[\]\"]/,"") if attribute_present?("diseases")
end
belongs_to :tenant
validates_uniqueness_of :mobileno
def self.by_plan_and_tenant(tenant_id)
tenant = Tenant.find(tenant_id)
if tenant.plan == 'free'
tenant.customers
else
tenant.customers
end
end
def client
Twilio::REST::Client.new Rails.application.secrets.twilio_account_sid, Rails.application.secrets.twilio_token
end
acct_sid = "Axxxxxxxxxxxxxx"
auth_token = "6cxxxxxxxxxxxxxxxxxxxxx"
twilio_no = "+16xxxxxxxxx"
acct_sid = ENV['twilio_account_sid']
auth_token = ENV['twilio_token']
twilio_no = ENV['twilio_no']
def send (to, body)
client.account.messages.create(
:messaging_service_sid => Rails.application.secrets.twilio_messaging_service_sid,
:from => "+1xxxxxxxxx1",
:to => '#{mobileno}',
:body => "Hi. Thanks a lot for signing up with us. Your UID is: #{uid}"
)
end
end

Twilio developer evangelist here.
After a long chat we changed the method name to send SMS messages from send (which is an important method for objects in Ruby) to send_sms.
Then we ensured the number had the right international code.
def send_sms()
client.account.messages.create(
:messaging_service_sid => Rails.application.secrets.twilio_messaging_service_sid,
:from => "+16312010201",
:to => "#+91{mobileno}",
:body => "Hi. Thanks a lot for signing up with us. Your UID is: #{uid}"
)
end
We then updated the Customers controller create action to send the SMS when the customer was successfully created:
def create
#customer = Customer.new(customer_params)
respond_to do |format|
if #customer.save
format.html {
#customer.send_sms
redirect_to root_url, notice: 'Customer data was successfully created.'
}
else
format.html { render :new }
end
end
end
So things work now.

Related

How to upload a file using the file_file_tag?

I want to upload file in form but do not want its field inside a model.
so using the file_filed_tag
at view:
<%= form_tag services_datainterchange_path, method: :post, remote: true do %>
<div class="row">
<div class="col-sm-3 col-md-3">
<div class="form-group">
<%= label_tag :file %>
<%= file_field_tag :file, required: true, class: "form-control", id: "upload_file" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= label_tag :name %>
<%= text_field_tag :name, nil, required: true, class: "form-control", id: "upload_file_name" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= label_tag :source_type %>
<%= select_tag :source_type, options_for_select(ApplicationRecord::SOURCE_TYPE), class: "form-control" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= label_tag :final_type %>
<%= select_tag :final_type, options_for_select(ApplicationRecord::FINAL_TYPE), class: "form-control" %>
</div>
</div>
<div class="col-sm-2 col-md-2">
<div class="form-group">
<%= submit_tag "Submit", class: "btn btn-primary" %>
</div>
</div>
</div>
<% end %>
At controller:
directory = "public/job_files"
Find.find( directory ) do |fpath|
if FileTest.file?( fpath )
fpath.clone(params[:file])
end
end
But file not upload the parameter do get submit of form.
Thanks
In controller:
name = params['file'].original_filename
uploaded_io = params['file']
File.open(Rails.root.join('public', 'job_files', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end

multiple forms in one view rails

am new to stack overflow..hoping support from all f u
i have employee form with personal details,contact details,salary details etc,arranged,but they are different controllers.i want to get all data in one form in employee view.employee contacts and other forms are not getting saved...help out...
`
<%= form_for(#employee, :html => {class: 'form-horizontal add_allignment employee_form', role: 'form'}) do |f| %>
<div class="form-group row">
<%= f.label :first_name, class: 'col-sm-3 form-control-label' %>
<div class="col-sm-9">
<%= f.text_field :first_name, class: 'form-control' %>
<span class="error-block"><%= validation_error(#employee, :first_name) %></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-0 col-sm-10">
<%= f.button "Submit", type: 'button', class: 'btn btn-primary btn-lg', onclick: 'submit_my_form(this)' %>
</div>
</div>
<% end %>
</div>
<div role="tabpanel" class="tab-pane in" id="nav-tabs-0-2">
<%= form_for(#employee.contact_components, :html => {class: 'form-horizontal add_allignment employee_form', role: 'form'}) do |e| %>
<div class="form-group row">
<%= e.label "P O Box", class: 'col-sm-3 form-control-label' %>
<div class="col-sm-9">
<%= e.text_field :po_box, class: 'form-control' %>
<span class="error-block"><%= validation_error(#employee, :po_box) %></span>
</div>
</div>
<div class="form-group row">
<%= e.label :permanent_address, class: 'col-sm-3 form-control-label' %>
<div class="col-sm-9">
<%= e.text_area :permanent_address, class: 'form-control' %>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-0 col-sm-10">
<%= e.button "Submit", type: 'button', class: 'btn btn-primary btn-lg', onclick: 'submit_my_form(this)' %>
</div>
</div>
<% end %>
</div>
</div>`
What you want is a nested form. It allows you to update different model attributes from a single form. That doc link will walk you through each change you need to make to the model, controller and views.

Rails hit new method on save of simpleform

So i have this method
def create
#newevent = Event.new(create_params)
#newevent.save!
flash[:success] = "Event Created"
redirect_to "/events"
end
And this form
<% provide(:title, "Edit user") %>
<h1>Editing event:
<%= #newevent.id %></h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= simple_form_for #newevent do |f| %>
<div class="form-group">
<%= f.label :eventname %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventname, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.input :event_type, :collection => ['Concert','Festival','Sports','Theatre'] %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventdesc %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventdesc, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventshortdesc %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventshortdesc, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :pagetitle %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :pagetitle, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :metatag %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :metatag, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventvenuename %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventvenuename, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.input :time, type: "time", :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.input :date, type: "date", :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :eventimage %>
<div class="row">
<div class="col-md-6">
<%= f.text_field :eventimage, :autofocus => true, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.check_box :eventready %>
<%= f.label :eventready, "Is event ready for SEO?" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<%= f.check_box :eventcomplete %>
<%= f.label :eventcomplete, "Is event ready for Public?" %>
</div>
</div>
</div>
<%= f.submit "Save changes", class: "btn btn-info" %>
<%= link_to "Delete", event_path(#newevent), :method => :delete, class: "btn btn-danger" %>
<% end %>
</div>
</div>
I'm currently populating this form with the edit method here
def edit
#newevent = Master.find(params[:id])
end
How can i go about making this pull in information from the Master table to auto populate the table but then save to the Event table?
Sam
What about a simple update method?
def update
#newevent = Event.find(params[:id])
if #newevent.update_attributes(params[:newevent])
redirect_to #user
else
render action: "edit"
end
end

Stripe form not submitting when charging customer.id in rails 4

I have a rails application that uses Stripe to process payments. When a user purchases an item for the first time, everything goes smoothly. I have added a checkbox to the charge form that allows a user to save their credit card for future transactions.
When I view a User object, I can see the Stripe customer ID saved to the customer_id field in the model, however when that user goes to purchase something with that stored card, the form will not submit (when I click the button "Buy with saved credit card" nothing happens).
charges_controller.rb (Relevant portion of the charges controller)
Stripe::Charge.create(
:amount => #gift.price * 100,
:currency => "cad",
:card => params[:existing_card_id],
:customer => #user.customer_id
)
if #charge.save
redirect_to gifts_path
flash[:notice] = "You have successfully sent #{#charge.recipient_email} a #{#gift.name}!"
CodeDelivery.send_code(#user, #gift, #charge, #code).deliver
#code.update_attributes(:used => true)
else
render 'charges/new'
flash[:alert] = "Something went wrong with your purchase."
end
new.html.erb (Second embedded form is the one for users with a customer_id)
<%= title "Redwood | " + #gift.name %>
<div class="container">
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><center><%= #gift.name %></center></h4>
</div>
<div class="modal-body">
<p><%= image_tag #gift.picture.url(:mobile) %></p>
<p><%= #gift.description %></p>
<p>$<%= #gift.price %></p>
<% if current_user.customer_id.nil? or current_user.customer_id == 0 %>
<%= form_for #charge, :url => { :action => :create }, :html => { :id => "payment-form" } do |f| %>
<%= f.hidden_field :gift_id, :value => #gift.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.text_field :sender_name, :class => "form-control", :placeholder => "Sender's Name" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.email_field :recipient_email, :class => "form-control", :placeholder => "Recipient's Email" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-earphone"></i>
<%= f.text_field :recipient_phone_number, :class => "form-control", :placeholder => "Recipient's Phone Number" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-pencil"></i>
<%= f.text_field :recipient_msg, :class => "form-control", :placeholder => "Message to Recipient" %>
</div>
<div class="form-group left-inner-addon ">
<i class="glyphicon glyphicon-credit-card"></i>
<%= text_field_tag :card_number, nil, :class => "form-control", :placeholder => "Credit Card Number", "data-stripe" => "number" %>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-4 left-inner-addon ">
<i class="glyphicon glyphicon-calendar"></i>
<%= text_field_tag :card_month, nil, :class => "form-control", :placeholder => "MM", "data-stripe" => "exp-month" %>
</div>
<div class="col-xs-5 left-inner-addon ">
<i class="glyphicon glyphicon-calendar"></i>
<%= text_field_tag :card_year, nil, :class => "form-control", :placeholder => "YYYY","data-stripe" => "exp-year" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-5 left-inner-addon ">
<i class="glyphicon glyphicon-ok-circle"></i>
<%= text_field_tag :card_cvv, nil, :class => "form-control", :placeholder => "CVV", "data-stripe" => "cvc" %>
</div>
</div>
</div>
<div class="checkbox"
<label>Save Credit Card</label>
<%= f.check_box :save_cc %>
</div>
<%= f.submit "Buy", :class => "btn btn-primary", :type => "submit" %>
<% end %>
<% else %>
<%= form_for #charge, :url => { :action => :create }, :html => { :id => "payment-form" } do |f| %>
<%= f.hidden_field :gift_id, :value => #gift.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.text_field :sender_name, :class => "form-control", :placeholder => "Sender's Name" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.email_field :recipient_email, :class => "form-control", :placeholder => "Recipient's Email" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-earphone"></i>
<%= f.text_field :recipient_phone_number, :class => "form-control", :placeholder => "Recipient's Phone Number" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-pencil"></i>
<%= f.text_field :recipient_msg, :class => "form-control", :placeholder => "Message to Recipient" %>
</div>
<%= f.submit "Buy With Saved Credit Card", :class => "btn btn-primary", :type => "submit" %>
<% end %>
<% end %>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
stripe.html (JS partial for Stripe)
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('pk_test_aoHfD0KHBMVsUzbr2KvpHQKi');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// 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="stripeToken" />').val(token));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#payment-form').submit(function(event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
My application currently can process payments fine for first time buyers, or for people who do not want to store their credit card information. The issue is with people who store their credit card.
This issue was solved by modifying the form ID of the second payment form (for users with saved credit cards) and removing the the :card attribute form the controller code.
new.html.erb
<%= title "Redwood | " + #gift.name %>
<div class="container">
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><center><%= #gift.name %></center></h4>
</div>
<div class="modal-body">
<p><%= image_tag #gift.picture.url(:mobile) %></p>
<p><%= #gift.description %></p>
<p>$<%= #gift.price %></p>
<% if current_user.customer_id.nil? or current_user.customer_id == 0 %>
<%= form_for #charge, :url => { :action => :create }, :html => { :id => "payment-form" } do |f| %>
<%= f.hidden_field :gift_id, :value => #gift.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.text_field :sender_name, :class => "form-control", :placeholder => "Sender's Name" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.email_field :recipient_email, :class => "form-control", :placeholder => "Recipient's Email" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-earphone"></i>
<%= f.text_field :recipient_phone_number, :class => "form-control", :placeholder => "Recipient's Phone Number" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-pencil"></i>
<%= f.text_field :recipient_msg, :class => "form-control", :placeholder => "Message to Recipient" %>
</div>
<div class="form-group left-inner-addon ">
<i class="glyphicon glyphicon-credit-card"></i>
<%= text_field_tag :card_number, nil, :class => "form-control", :placeholder => "Credit Card Number", "data-stripe" => "number" %>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-4 left-inner-addon ">
<i class="glyphicon glyphicon-calendar"></i>
<%= text_field_tag :card_month, nil, :class => "form-control", :placeholder => "MM", "data-stripe" => "exp-month" %>
</div>
<div class="col-xs-5 left-inner-addon ">
<i class="glyphicon glyphicon-calendar"></i>
<%= text_field_tag :card_year, nil, :class => "form-control", :placeholder => "YYYY","data-stripe" => "exp-year" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-5 left-inner-addon ">
<i class="glyphicon glyphicon-ok-circle"></i>
<%= text_field_tag :card_cvv, nil, :class => "form-control", :placeholder => "CVV", "data-stripe" => "cvc" %>
</div>
</div>
</div>
<div class="checkbox"
<label>Save Credit Card</label>
<%= f.check_box :save_cc %>
</div>
<%= f.submit "Buy", :class => "btn btn-primary", :type => "submit" %>
<% end %>
<% else %>
<%= form_for #charge, :url => { :action => :create }, :html => { :id => "saved-payment-form" } do |f| %>
<%= f.hidden_field :gift_id, :value => #gift.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.text_field :sender_name, :class => "form-control", :placeholder => "Sender's Name" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-send"></i>
<%= f.email_field :recipient_email, :class => "form-control", :placeholder => "Recipient's Email" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-earphone"></i>
<%= f.text_field :recipient_phone_number, :class => "form-control", :placeholder => "Recipient's Phone Number" %>
</div>
<div class="form-group left-inner-addon">
<i class="glyphicon glyphicon-pencil"></i>
<%= f.text_field :recipient_msg, :class => "form-control", :placeholder => "Message to Recipient" %>
</div>
<%= f.submit "Buy With Saved Credit Card", :class => "btn btn-primary", :type => "submit" %>
<% end %>
<% end %>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
charges_controller.rb
Stripe::Charge.create(
:amount => #gift.price * 100,
:currency => "cad",
:customer => #user.customer_id
)
if #charge.save
redirect_to gifts_path
flash[:notice] = "You have successfully sent #{#charge.recipient_email} a #{#gift.name}!"
CodeDelivery.send_code(#user, #gift, #charge, #code).deliver
#code.update_attributes(:used => true)
else
render 'charges/new'
flash[:alert] = "Something went wrong with your purchase."
end

How do I fix this form the Rails way?

I want to have all the errors appear on top of their respective areas.
I ran an if statement with any? on the first one but I know I am repeating myself and have to do it the Rails way.
Any help?
<%= form_for #movie, :html => {:class => "form-horizontal"} do |f| %>
<div class="control-group">
<% if #movie.errors[:title].any? %>
<div class="alert alert-error"><%= #movie.errors[:title].to_sentence %></div>
<% end %>
<%= f.label :title, :class => "control-label" %>
<div class="controls">
<%= f.text_field :title %>
</div>
</div>
<div class="control-group">
<div class="alert alert-error"><%= #movie.errors[:description].to_sentence %></div>
<%= f.label :description,:class => "control-label" %>
<div class="controls">
<%= f.text_area :description, :class => "span8", :rows => "10" %>
</div>
</div>
<div class="control-group">
<div class="alert alert-error"><%= #movie.errors[:rating].to_sentence %></div>
<%= f.label :rating, :class => "control-label" %>
<div class="controls">
<%= f.select :rating, Movie::RATINGS, prompt: "Pick one" %>
</div>
</div>
<div class="control-group">
<div class="alert alert-error"><%= #movie.errors[:total_gross].to_sentence %></div>
<%= f.label :total_gross, :class => "control-label" %>
<div class="controls">
<%= f.number_field :total_gross %>
</div>
</div>
<div class="control-group">
<div class="alert alert-error"><%= #movie.errors[:released_on].to_sentence %></div>
<%= f.label :released_on, :class => "control-label" %>
<div class="controls">
<%= f.date_select :released_on, :order => [:month, :day, :year], :prompt => { :month => 'Select month',:day => 'Select day', :year => 'Select year' }, :start_year => 1950 %>
</div>
</div>
<div class="control-group" >
<%= f.label :image_file_name, :class => "control-label" %>
<div class="controls">
<%= f.text_field :image_file_name %>
</div>
</div>
<div class="form-actions">
<%= f.submit :class => "btn btn-success btn-large" %> <%= link_to "Cancel", root_path, class: "btn btn-danger btn-large" %>
</div>
<% end %>
Here's a solution that will be more DRY and won't necessitate gems like simple_form.
Create a partial for your control group and replace the field name and form field helper with variables:
# File: _control_group.html.erb
<% show_errors = true if show_errors.nil? %>
<div class="control-group">
<% if #movie.errors[field_name].present? && show_errors %>
<div class="alert alert-error">
<%= #movie.errors[field_name].to_sentence %>
</div>
<% end %>
<%= label_tag field_name, :class => "control-label" %>
<div class="controls">
field_helper
</div>
</div>
Then replace these items in your form with a partial render and pass the appropriate code in through the parameters:
<%= form_for #movie, :html => {:class => "form-horizontal"} do |f| %>
<%= render "control_group", field_name: :title, field_helper: f.text_field(:title) %>
<%= render "control_group", field_name: :description, field_helper: f.text_area(:description, :class => "span8", :rows => "10") %>
<%= render "control_group", field_name: :rating, field_helper: f.select(:rating, Movie::RATINGS, prompt: "Pick one") %>
<%= render "control_group", field_name: :total_gross, field_helper: f.number_field(:total_gross) %>
<%= render "control_group", field_name: :released_on, field_helper: f.date_select(:released_on, :order => [:month, :day, :year], :prompt => { :month => 'Select month',:day => 'Select day', :year => 'Select year' }, :start_year => 1950) %>
<%= render "control_group", field_name: :image_file_name, field_helper: f.text_field(:image_file_name), show_errors: false %>
<div class="form-actions">
<%= f.submit :class => "btn btn-success btn-large" %> <%= link_to "Cancel", root_path, class: "btn btn-danger btn-large" %>
</div>
<% end %>
Ran into a similar problem.
Using simple_form worked for me. See an example here

Resources