我試圖實現一個控制器方法,其中一個帳戶向另一個帳戶發送一筆錢。在accnts_controller
的代碼如下:努力正確實現自定義導軌控制器方法
def donate(amt, client)
if creator?
raise 'Only Patron accounts can donate'
else
@client = Accnt.find(client)
@client.balance += amt
@accnt.balance -= amt
@client.save
@accnt.save
end
end
(注:在我的控制,我有一個行動之前它設置了@accnt
對象)
要做到這一點,我寫了下面的定製路線:
patch 'accnts/:id/donate' => 'accnts#donate'
我一直有兩個問題在實施該方法,但遠不是最大的是,我不知道怎麼寫,可以將值傳遞給amt
和捲曲請求參數。我幾乎完全使用cURL來測試我的後端的功效,因爲我所在的程序並沒有教會我們如何使用rails視圖。我怎樣才能寫出一個curl請求來測試我的方法?
編輯:我的完整控制器代碼。這是用腳手架生成的,並且被稍微修改
class AccntsController < OpenReadController
before_action :set_accnt, only: %i[show update donate destroy]
# GET /accnts
def index
@accnts = Accnt.all
render json: @accnts
end
# GET /accnts/1
def show
render json: @accnt
end
# POST /accnts
def create
if current_user.accnt
raise 'Already has an account'
else
@accnt = Accnt.new(accnt_params)
@accnt.user = current_user
if @accnt.save
render json: @accnt, status: :created
else
render json: @accnt.errors, status: :unprocessable_entity
end
# render json: @accnt, status: :created, location: @accnt if @accnt.save
end
end
# PATCH/PUT /accnts/1
def update
if @accnt.update(accnt_params)
render json: @accnt
else
render json: @accnt.errors, status: :unprocessable_entity
end
end
# amt is the amount to be sent from the patron to the client, client is the client ID
def donate(amt, client)
# furthermore, I cannot say for certain whether this method of passing parameters is viable in rails
if creator?
raise 'Only Patron accounts can donate'
else
# Very easily could be logical errors here
@client = Accnt.find(client)
@client.balance += amt
@accnt.balance -= amt
@client.save
@accnt.save
end
end
# DELETE /accnts/1
def destroy
@accnt.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
# To be used as a before method to determine whether or not the account in
# question is a creator account
def creator?
creator
end
def set_accnt
@accnt = Accnt.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def accnt_params
params.require(:accnt).permit(:user_id, :user_name, :balance, :creator, :content_type, :content_list)
end
end
對於捲曲的要求,我還沒有真正寫出來超出了:
API="http://localhost:4741"
URL_PATH="/accnts"
curl "${API}${URL_PATH}/${ID}/donate" \
--include \
--request PATCH \
--header "Content-Type: application/json" \
--header "Authorization: Token token=$TOKEN" \
--data
echo
你可以添加你的控制器和cURL請求嗎? –
如何定義'amt'和'client'? (它使用什麼參數?)並且請顯示你目前的cURL嘗試的樣子,否則我們無法知道你做錯了什麼。 –
我已經用所需的代碼更新了我的答案。 @TomLord; amt是一個浮動,用於修改捐款方法帳戶和目標帳戶的餘額屬性,而客戶端是捐款目標帳戶的id屬性。正如你所看到的,我的curl請求尚未完成,因爲我不知道如何將值傳遞給方法參數。 – d00medman