【问题标题】:Defining custom methods in Rails在 Rails 中定义自定义方法
【发布时间】:2012-11-07 01:59:07
【问题描述】:

我刚刚开始使用 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) 但是当我点击执行链接时,我得到了路由错误: [POST] "/transactions/6"

目前我的路线(routes.rb)设置如下:

resources :transactions do
       member do
       post :execute
       end
   end

  resources :accounts

如何设置路由以便它可以处理我的方法? 在此先感谢

【问题讨论】:

    标签: ruby-on-rails methods routes


    【解决方案1】:

    您在这里尝试做的不是添加一个新方法,而是一个新的“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
    

    然后更新您的执行链接并将“事务”替换为正确的路径查找器,并将方法设置为 :post。

    link_to "Execute", execute_transaction_path(transaction), method: :post
    

    【讨论】:

      【解决方案2】:

      小区别:将方法名从符号改为字符串。

      resources :transactions do
        member do
          post "execute"
        end
      end
      

      查看Rails Routing Guide

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多