我知道这是你不能在rails内部做的事情或者不应该这样做但我需要以某种方式获取用户在表单字段中输入的金额并使用该值。
这就是我的模型的样子
class Deposit < ActiveRecord::Base
belongs_to :credit_card
belongs_to :user
validates :credit_card, presence: true
validates :user, presence: true
validates :tx_type, inclusion: %w(debit credit)
# validates :amount, presence: true, numericality: true
before_create :add_transaction_to_merchant
after_create :update_user_balance
attr_readonly :credit_card_id, :user_id, :fee_id, :tx_type, :status, :merchant_tx_id
attr_accessible :tx_type, :amount, :status, :merchant_tx_id, :credit_card_id,
:user_id, :user
def amount
return attributes[:amount] if attributes[:amount]
set_amount
end
def tx_type
attributes[:tx_type] || 'debit'
end
def send_receipt
Resque.enqueue(PaymentCompletedSender, self.id)
end
def update_user_balance
user_balance =user.balance + set_amount
user.balance = user_balance
user.save
end
private
def add_transaction_to_merchant
set_amount
return false if credit_card.nil?
return true unless amount > 0
result = Braintree::Transaction.sale(
amount: amount,
payment_method_token: credit_card.token,
options: { submit_for_settlement: true }
)
if result.success?
self.merchant_tx_id = result.transaction.id
# status will be authorized or submitted_for_settlement
self.status = result.transaction.status
else
errors.add(:base, result.message)
if result.transaction.nil?
# validation errors prevented transaction from being created
logger.error(result.errors)
else
self.merchant_tx_id = result.transaction.id
# status will be processor_declined, gateway_rejected, or failed
self.status = result.transaction.status
end
end
end
def set_amount
attributes[:amount]
end
end
控制器:
# POST /deposits
# POST /deposits.json
def create
@deposit = Deposit.new(params[:deposit])
@deposit.user = current_user
@deposit.credit_card = current_user.credit_cards.try(:first)
binding.pry
respond_to do |format|
if @deposit.save
format.html { redirect_to "/", notice: 'Deposit was successfully created.' }
format.json { render json: @deposit, status: :created, location: @deposit }
else
format.html { render action: "new" }
format.json { render json: @deposit.errors, status: :unprocessable_entity }
end
end
end
这就是表格发送的参数
{"utf8"=>"✓",
"authenticity_token"=>"r0M0sRr7QO9kl0IWrJSgvj45DFrC6mbbuA+ttgEaUI0=",
"deposit"=>{"amount"=>"100"},
"commit"=>"Pay Now"}
有关如何从模型中的表单返回金额值的任何想法?
答案 0 :(得分:1)
@deposit = Deposit.new(params[:deposit])
如果您删除模型中的amount
和set_amount
方法,则应该只能在模型中使用amount
或self.amount
,以便以下内容够了
def add_transaction_to_merchant
return false if credit_card.nil?
return true unless amount > 0
result = Braintree::Transaction.sale(
amount: amount,
payment_method_token: credit_card.token,
options: { submit_for_settlement: true }
)