Search code examples
ruby-on-railsruby-on-rails-4nested-resources

Nested controller Resources, how to do update and destroy?


followed a tutorial to help me create instances within a controller. In other words transactions are created on the envelope controller. Like comments on a blog post.

Everything is working perfectly, but I don't know how to edit a transaction now or destroy one. All I need is to find how to edit an existing thing. Let me show you what I have so far:

in views/envelopes/edit (the form code was copied from where you can create new transactions)

 <% @envelope.transactions.each do |transaction|%>
   <%= form_for [@envelope, @envelope.transactions.build] do |f| %> <!--??? NEED EDIT INSTEAD OF BUILD ???-->
     <%= f.text_field :name, "value" => transaction.name %>
     <%= f.text_field :cash, "value" => transaction.cash %>
     <%= f.submit "Submit" %> 
   <% end %>
   <%= link_to "Remove", root_path %>  <!--??? WANT TO REMOVE TRANSACTION ???-->
 <% end %>

in routes.rb

  resources :envelopes do 
    resources :transactions
  end

in transaction controller

class TransactionsController < ApplicationController
  def create
    @envelope = Envelope.find(params[:envelope_id])
    @transaction = @envelope.transactions.build(transaction_params)#(params[:transaction])
    @transaction.save

    @envelope.update_attributes :cash => @envelope.cash - @transaction.cash

    redirect_to edit_envelope_path(@envelope)
  end

  def destroy
    # ???
  end

  def update
    # ???
  end

  def transaction_params
    params.require(:transaction).permit(:cash, :name, :envelope_id)
  end
end

Solution

  •   def update
        @transaction = @envelope.transactions.find(params[:id])
        if @transaction.update(transaction_params)
          redirect to @envelope, notice: 'Transaction was successfully updated'
        else
          redirect_to @envelope, notice: 'Transaction was not updated'
        end
      end
    
      def destroy
        @transaction.destroy
        redirect_to @envelope, notice: 'Text here'
      end