[英]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.