我有兩個控制器,一個是付款,一個是交易,我需要在付款的創建方法中呼叫交易的創建方法。這樣每次我創建付款時都會自動創建交易。我應該如何處理這個?
module Api class PaymentsController < ApplicationController before_action :set_payment, only: %i[ show update destroy ] def index @payments = Payment.all render json: @payments end def show render json: @payment end def create @payment = Payment.new(payment_params) if @payment.save render json: 'Payment Is Made sucessfully'.to_json, status: :ok else render json: @payment.errors, status: :unprocessable_entity end end private def payment_params params.permit(:currency, :amount, :payment_type, :payment_address) end end end
module Api class TransactionsController < ApplicationController before_action :set_transaction, only: %i[show update destroy] def index @transactions = Transaction.all render json: @transactions end def show render json: @transaction end # POST /transactions def create @transaction = Transaction.new(transaction_params) if @transaction.save render json: @transaction, status: :created, location: @transaction else render json: @transaction.errors,status::unprocessable_entity end end private def transaction_params params.permit(:transaction_type, :bank_name, :debit, :credit, :total_amount) end end end
uj5u.com熱心網友回復:
首先要注意,MVC 只是一種組織代碼的約定或好方法。
你可以簡單地做:
def create
@transaction = Transaction.new(transaction_params)
# You'll have to figure out how to get the params in here - maybe they are all derived from the transaction?
@payment = Payment.new()
@payment.save
# handle payment error here too like below
if @transaction.save
render json: @transaction, status: :created, location: @transaction
else
render json: @transaction.errors,status::unprocessable_entity
end
end
但是,這對于可重用代碼來說并不好。
我們有 2 個選項 - 將其放入模型或引入服務。
在事務模型中,我們可以創建如下函式:
class Transaction
...
def self.create_with_payment(params)
Transaction.create(params)
Payment.create(params)
# do whatever here to create and associate these
end
或者我們可以引入一個服務物件:
class TransactionPaymentCreator
def call(params)
Transaction.create(params)
Payment.create(params)
end
end
然后你可以在你的控制器中呼叫它:
def create
service = TransactionPaymentCreator.new
service.call
end
我省略了很多細節,比如如何設定這些東西 - 但我希望向你傳達一般細節 - 你有 3 個選項來完成這項作業。
如果您決定走這條路,這里有一篇關于閱讀更多服務物件的好文章和資源:
https://www.honeybadger.io/blog/refactor-ruby-rails-service-object/
uj5u.com熱心網友回復:
我的方法是對您的付款模型進行回呼:
# payment.rb
after_create :create_transaction
def create_transaction
Transaction.create(payment_id: id) # or whatever params you need in the transaction
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497363.html