In the seemingly never-ending quest to understand Braintree's obfuscated documentation, I ended up creating my own update UI with a list of BTPaymentMethod
The Braintree docs say to update a payment method with a token (which I see in my online sandbox vault). How do I retrieve an indivdual customers card token to update?
I'm using -[BTClient fetchPaymentMethodsWithSuccess:failure:], which returns BTPaymentMethodwhich only has thepayment_nonce property. Trying to update with this property return an error CVV is required.
def update_payment_default
#customer = Customer.where(id: params[:id]).first
if #customer.present?
#string = "customer_" + #customer.id.to_s
result = Braintree::Customer.update(
"my_customer_id"
:credit_card => {
:payment_method_nonce => params[:payment_method_nonce],
:options => {
:make_default => true
}
}
)
if result.success?
respond_to do |format|
msg = {:status => "SUCCESS", :message => "Updated payment payment method"}
format.json { render :json => msg } # don't do msg.to_json
end
else
respond_to do |format|
msg = {:status => "FAILED", :message => result.errors}
format.json { render :json => msg } # don't do msg.to_json
end
end
end
Related
I have written code for Phone verification code but it's not working.
Main problem is, that user can put any number for verification. That means verification_number don't work.
def phone_verification
u = User.find(params[:user_id])
if params[:verification_code]
if u.verification_number.to_s == params[:verification_code].to_s
u.phone_verified = true
u.save
respond_to do |format|
format.js { render :status => :ok }
end
end
else
u.update_attributes(phone: params[:phone], country_code_id: params[:prefix], verification_number: rand(10000))
u.save
# Phone verification
#full_phone = "#{CountryCode.find(params[:prefix]).calling_code}#{params[:phone]}"
number_to_send_to = Rails.env.production? || Rails.env.staging? ? #full_phone : TEST_MOBILE
Rails.logger.debug "-- Verification code: #{u.verification_number}"
#twilio_client = Twilio::REST::Client.new(Mekomy::Application.config.twilio_account_sid, Mekomy::Application.config.twilio_auth_token)
begin
#twilio_client.account.sms.messages.create(
:from => Mekomy::Application.config.twilio_phone_number,
:to => number_to_send_to,
:body => "Please add this verification code when prompt: #{u.verification_number}"
)
respond_to do |format|
format.js { render :status => :ok }
end
rescue
Rails.logger.debug "-- Some error"
end
end
end
Can someone help me to find, where I was wrong?
Thank you all!
I have the following code segment
def range
respond_to do |format|
if params[:start] && params[:end]
begin
dstart = Time.parse(params[:start])
dend = Time.parse(params[:end])
rescue => e
format.json { render :json => { :status => :unprocessable_entity, :error => e.message }} and return
end
...
And it works totally fine and makes it to the stuff at the bottom...
...
format.json { render :json => { :status => :ok, :posts => #res.to_json(:only => [:date, :content, :user_id]) } }
else
format.json { render :json => { :status => :unprocessable_entity, :error => "must have a _start_ and _end_ date" } }
...
The problem is when an exception occurs and the rescue section is called, Rails does not respond with json but instead tells me "Template Missing." Is something wrong with my syntax?
D'oh, turns out I don't need the format.json bit. Why, exactly, though?
Consider this example regarding show action to understand the error
class ModelsController
.
.
def show
#model = Model.find(params[:id])
respond_to do |format|
format.html
format.js
end
end
end
In this case, if the request is of type html then rails by convention searcher for a file
app/views/models/show.html.erb.
But if the request is of type js then rails will search for app/views/models/show.js.erb.
If these files does not exist then rails will throw template missing error
so if you are only responding to json then you can do
respond_to do |format|
format.json do
begin
..
rescue
render :json => { }
end
end
I'm using ActiveMerchant with Authorize.net and already setup 2 models Order and Transaction. (http://railscasts.com/episodes/145-integrating-active-merchant)
I would like to get error message from the transaction if error occurred then output in flash message. Here is my code:
#order_controller.rb
def create
#order = Order.new(params[:order])
respond_to do |format|
if #order.save
if #order.purchase
format.html { redirect_to(#order, :notice => 'Order was successfully created.') }
format.xml { render :xml => #order, :status => :created, :location => #order }
else
flash[:error] = #order.transactions.response
format.html { render :action => "new" }
end
else
format.html { render :action => "new" }
format.xml { render :xml => #order.errors, :status => :unprocessable_entity }
end
end
end
And here is my transaction model:
#models/order_transaction.rb
class OrderTransaction < ActiveRecord::Base
belongs_to :order
serialize :params
def response=(response)
self.success = response.success?
self.authorization = response.authorization
self.message = response.message
self.params = response.params
rescue ActiveMerchant::ActiveMerchantError => e
self.success = false
self.authorization = nil
self.message = e.message
self.params = {}
end
end
The transaction data has been saved to the database as below:
#models/order.rb
class Order < ActiveRecord::Base
has_many :transactions, :class_name => "OrderTransaction"
attr_accessor :card_type, :card_number, :card_month, :card_year, :card_verification
def purchase
response = GATEWAY.purchase(charge_amount, credit_card, purchase_options)
transactions.create!(:action => "purchase", :amount => charge_amount, :response => response)
response.success?
end
...
end
I want to flash up this transaction error message when transaction failed. And what would I should do to get these errors if I have 2 transactions for one order.?
Any help would be much appreciated.
Thanks!
Currently I verify that there are no duplicated Members when trying to create a new Member and add it to a Team.
members_controller.rb
def create
#team = current_team
player = Player.find(params[:player_id])
#member = #team.add_player(player.id)
respond_to do |format|
if #member.save
format.html { redirect_to(#team, :notice => 'Member was successfully added.') }
format.js { #current_member = #member }
format.xml { render :xml => #member,
:status => :created, :location => #member }
else
format.html { redirect_to(#team, :notice => 'Member already exists.') }
format.xml { render :xml => #member.errors,
:status => :unprocessable_entity }
end
end
end
team.rb
def add_player(player_id)
current_member = members.build(:player_id => player_id)
current_member
end
I want to add some logic to my add_player method in team.rb that checks various properties of the player that is being added. This action will require multiple failure messages, other than 'Member already exists.' How do I do this in the Model layer?
You can create custom errors on ActiveRecord models. These custom errors can have their own messages, which you can query in your controller if the save is not successful:
# app/models/team.rb
def add_player(player_id)
current_member = members.build(:player_id => player_id)
errors.add(:player_id, 'Custom error message here') if condition
errors.add(:base, 'Custom error message here') if condition
current_member
end
# app/controllers/members_controller.rb
def create
#team = current_team
player = Player.find(params[:player_id])
#member = #team.add_player(player.id)
respond_to do |format|
if #member.save
format.html { redirect_to(#team, :notice => 'Member was successfully added.') }
format.js { #current_member = #member }
format.xml { render :xml => #member,
:status => :created, :location => #member }
else
format.html { redirect_to(#team, :notice => #member.errors.full_messages) }
format.xml { render :xml => #member.errors,
:status => :unprocessable_entity }
end
end
end
More information on custom ActiveRecord validation errors here: http://api.rubyonrails.org/v2.3.8/classes/ActiveRecord/Errors.html#M001725
The controller logic to display all errors from base worked. However, I was not able to add errors from the add_player method as Ben suggested. I instead created separate custom validations as such:
Team.rb
validate validation_name
def validation_name
if condition
errors.add_to_base "Error Message"
end
end
I have been using attachment_fu on a project for a long time and all was fine but now as I am trying to bring the project up to rails 2.3.3 I am running into a strange bug that is driving me nuts. The Attachment, a logo in this case, validates correctly on create but does not fail validation on update. I have debugged it and it fails the intial validate but does not seem to throw an exception or at least not one that is caught by my rescue in the controller. Seems like I have tried everything but can't figure this one out.
Controller:
# POST /tournaments
# POST /tournaments.xml
def create
# Build tournament
#tournament = Tournament.new(params[:tournament].merge(:user_id => current_user.id) )
# Save the uploaded attachments
params[:uploads].each do |upload|
#tournament.documents << Document.new({:uploaded_data => upload[:document]}.merge(:description => upload[:description]))
end unless params[:uploads].nil?
# if supplied save an event logo
#logo = Logo.new({:uploaded_data => params[:logo][:upload_data]}) unless params[:logo].nil? or params[:logo][:upload_data].blank?
#tournament.logo = #logo unless #logo.nil?
respond_to do |format|
begin
Tournament.transaction do
#tournament.logo.save! unless #tournament.logo.nil?
#tournament.save!
end
flash[:notice] = 'Tournament was successfully created.'
format.html { redirect_to tournament_url(#tournament) }
format.xml { head :created, :location => tournament_url(#tournament) }
rescue
flash[:notice] = 'Errors prevented your Tournament from being saved'
format.html { render :action => "new" }
format.xml { render :xml => #tournament.errors, :status => :unprocessable_entity }
end
end
end
# PUT /tournaments/1
# PUT /tournaments/1.xml
def update
#tournament = Tournament.find(params[:id])
#tournament.user_id = session[:orig_user_id]
respond_to do |format|
begin
Tournament.transaction do
# Update Logo if necessary
unless params[:logo][:upload_data].blank?
#tournament.logo.destroy unless #tournament.logo.nil?
#tournament.logo = Logo.new({:uploaded_data => params[:logo][:upload_data]}.merge(:user_id => current_user.id))
end
# Save any uploaded documents
params[:uploads].each do |upload|
#tournament.documents << Document.new({:uploaded_data => upload[:document]}.merge(:description => upload[:description]))
end unless params[:uploads].nil?
# Update Tournamnet Attributes
#tournament.attributes = params[:tournament]
# Save the Tournament
#tournament.save!
end
flash[:notice] = 'Tournament was successfully updated.'
format.html { redirect_to tournament_url(#tournament) }
format.xml { head :ok, :location => tournament_url(#tournament) }
rescue
flash[:notice] = 'Errors prevented your Tournament from being updated'
format.html { render :action => "edit" }
format.xml { render :xml => #tournament.errors, :status => :unprocessable_entity }
end
end
end
Logo Model:
class Logo < Asset
validate_on_create :attachment_valid?
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 4.megabytes,
:resize_to => '810x150>',
:processor => :ImageScience,
:thumbnails => { :thumb => '270x50>' }
def attachment_valid?
content_type = attachment_options[:content_type]
unless content_type.nil? || content_type.include?(self.content_type)
errors.add(:upload_data, " * must be an image file (jpg, gif, or png)")
end
size = attachment_options[:size]
unless size.nil? || size.include?(self.size)
errors.add(:upload_data, "* image must be 4MB or less")
end
end
before_thumbnail_saved do |thumbnail|
record = thumbnail.parent
thumbnail.user_id = record.user_id
thumbnail.listing_id = record.listing_id
end
end
I am running the following
Rails 2.3.3
image_science 1.2.0
Thanks
--Tim
You could also use a :before_save callback to test the object. If it is invalid, raise an exception.
try adding:
validate_on_update :attachment_valid?