I have just started using Rails and I am trying to build a banking app. I am having trouble setting up transactions between accounts.
I have currently scaffolded Transaction and Account. In my transaction page I can create a list of transaction with each transaction containing information about the source account, amount to transfer and the destination account. However, at the end of the page I would like a link or a button that processes all the transactions on the page and clears the page. Thus, modifying all the specified account balances.
Below is the steps I took in going about it.
1) In transaction model (transaction.rb model) define process method
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) Then create a method in transaction controller call 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) Then define the a link to display on the transaction page (shown below):
<% @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) But when I click the Execute link I get the routing error:
[POST] “/transactions/6”
Currently my routes(routes.rb) are setup as follows:
resources :transactions do
member do
post :execute
end
end
resources :accounts
How do I setup the routes so that it may process my method?
Thanks in advance
What you’re trying to do here is not add a new method, but a new ‘HTTP verb’. Don’t do it. You’ll likely receive a nasty message like this:
In the console run ‘
rake routes‘ and be sure you have the route for execute registered. Something like:Then update your execute link and replace ‘transaction’ with the proper path finder, and set the method to :post instead.