我想用我的cash_in_order模型处理Stripe错误。
> CashInOrder.new
=> #<CashInOrder:0x000055e51bee03d0
id: nil,
deposit_id: nil,
order_sum: nil,
stripe_charge_id: nil,
created_at: nil,
updated_at: nil>
我附加到cash_in_order表单select_tag以选择支付卡
<%= form_with model: @cash_in_order, class: 'form', id: 'cash_in_order' do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= select_tag 'cash_in_order[order_source]', options_for_select(cards.collect{ |c| ["**** **** **** #{c.last4}", c.id] }, cards.first.id), class: "form-control" %>
<br>
<%= f.text_field :order_sum, class: "form-control", placeholder: "Amount" %>
<br>
<%= f.submit "add founds", class: "btn btn-default" %>
<% end %>
并添加到cash_in_order_params order_source属性
class CashInOrdersController < ApplicationController
create
@user = current_user
@deposit = @user.deposit
@cash_in_order = @deposit.cash_in_orders.build
if current_user and current_user.deposit.id == @deposit.id
@cash_in_order.save
end
respond_to do |format|
if @cash_in_order.save
format.html { redirect_to @deposit, notice: 'Founds were added to deposit!!' }
format.json {head :no_content}
format.js { flash.now[:notice] = "Founds were added to deposit!" }
else
format.html { redirect_to @deposit, notice: 'Founds were not added to deposit! Something was going wrong' }
format.json { render json: @cash_in_order.errors.full_messages, status: :unprocessable_entity }
end
end
end
private
def cash_in_order_params
params.require(:cash_in_order).permit(:order_source, :order_sum)
end
end
提交表格后,我在控制台中看到
Started POST "/cash_in_orders" for ::1 at 2020-09-29 07:46:11 -0400
Processing by CashInOrdersController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Qgznx99ZUDwBG4R7moEE1gIP9o7FCpzbQh+FO8ccosrfMy5V7O5ydg/b6QvT7jZWUmQKtz+JDRO5rM4msDhzrw==", "cash_in_order"=>{"order_source"=>"card_1HSnL8KcFr6ZSgIRyUZUQrtE", "order_sum"=>""}, "commit"=>"add founds"}
order_sum params我留空以从Stripe获得错误(大于零(。
为了处理条纹错误,我在现金订单模型中创建了验证器
class CashInOrder < ApplicationRecord
validate :is_cashed_in
private
def is_cashed_in
card = self.deposit.user.retrieve_card(self.order_source) #Here is my error!!!
Stripe::Charge.create(:amount => (amount.to_f*100).to_i, :currency => 'usd', :source => card.id, :customer => self.deposit.user.stripe_customer_id)
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
end
我得到错误
CashInOrdersController#创建时出现NoMethodError
#CashInOrder的未定义方法"order_source":0x00007f42f8f129e8
当然,我的模型没有order_source atrribute,但我把它添加到了cash_in_order_params中,我可以在请求我的服务器时看到它
所以我的问题是如何将此order_source参数正确发送到模型验证器?
感谢您的预付款!
尝试使用attr_accessor
class CashInOrder < ApplicationRecord
attr_accessor :order_source
end