[英]Defining custom methods in Rails
我剛剛開始使用Rails,正在嘗試構建銀行應用程序。 我在設置帳戶之間的交易時遇到麻煩。
我目前有腳手架交易和帳戶。 在我的交易頁面中,我可以創建一個交易列表,其中每個交易都包含有關源帳戶,轉賬金額和目標帳戶的信息。 但是,在頁面末尾,我想要一個鏈接或一個按鈕,用於處理頁面上的所有事務並清除頁面。 因此,修改所有指定的帳戶余額。
以下是我為此采取的步驟。
1)在事務模型(transaction.rb模型)中定義處理方法
class Transaction < ActiveRecord::Base
def proc (transaction)
# Code processes transactions
@account = Account.find(transaction.from_account)
@account.balance = @account.balance - transaction.amount
@account.update_attributes(params[:account]) #update the new balance
end
end
2)然后在事務控制器調用execute中創建一個方法
def execute
@transaction = Transaction.find(params[:id])
proc (@transaction)
@transaction.destroy
respond_to do |format|
format.html { redirect_to transactions_url }
format.json { head :no_content }
end
3)然后定義一個鏈接以顯示在交易頁面上(如下所示):
<% @transactions.each do |transaction| %>
<tr>
<td><%= transaction.from_account %></td>
<td><%= transaction.amount %></td>
<td><%= transaction.to_account %></td>
<td><%= link_to 'Execute', transaction, confirm: 'Are you sure?', method: :execute %></td>
<td><%= link_to 'Show', transaction %></td>
<td><%= link_to 'Edit', edit_transaction_path(transaction) %></td>
<td><%= link_to 'Destroy', transaction, confirm: 'Are you sure?', method: :delete %></td>
<td><%= transaction.id%></td>
</tr>
<% end %>
4)但是,當我單擊Execute鏈接時,出現路由錯誤:[POST]“ / transactions / 6”
目前,我的routes(routes.rb)設置如下:
resources :transactions do
member do
post :execute
end
end
resources :accounts
如何設置路線,以便可以處理我的方法? 提前致謝
您要在此處執行的操作不是添加新方法,而是添加新的“ HTTP動詞”。 不要這樣 您可能會收到這樣的討厭消息:
!! Unexpected error while processing request: EXECUTE, accepted HTTP methods are OPTIONS,
GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK,
UNLOCK, VERSION-CONTROL, REPORT, CHECKOUT, CHECKIN, UNCHECKOUT, MKWORKSPACE, UPDATE, LABEL,
MERGE, BASELINE-CONTROL, MKACTIVITY, ORDERPATCH, ACL, SEARCH, and PATCH
在控制台中運行“ rake routes
”,並確保您已注冊了執行路徑。 就像是:
execute_transaction
然后更新您的執行鏈接,並用正確的路徑查找器替換“ transaction”,然后將方法設置為:post。
link_to "Execute", execute_transaction_path(transaction), method: :post
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.