これは 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"}
モデルのフォームから金額の値を返す方法について何か考えはありますか?