Wisely Wong
Wisely Wong

Reputation: 380

Delete a row of data with a destroy button in Ruby

I have an index of all items from database listed in my view. I want to create a destroy button to destroy the current record in the database using Ruby on Rails 4. Here is my code:

<div>
   <h1>All Incomes</h1>

  <% @user_incomes.each do |income| %>
  <div>
    <p><%= income.title %></p>
    <p><%= income.description %></p>
    <p><%= number_to_currency(income.amount) %>
    <p><%= income.user_id %></p>
    <%= button_to "Destroy", {action: "destroy", id: income.id}, method: :destroy, data: { confirm: "Are you sure?" } %>
  </div>
    <br />
  <%end%>
</div>

My Income Controller:

class IncomesController < ApplicationController
  before_action :authorize, only: [:new, :index, :show, :create]
  def index
    @incomes = Income.all #income refers to the db model income
    @user_incomes = Income.all.where(:user_id=>current_user.id)
  end

  def show
    @income = Income.find(params[:id])
  end

  def new
    @income = Income.new
  end

  def create
    @income = Income.create(income_params)
  end

  def destroy
    @income.destroy
  end

  ## Strong Parameters alias Rails 3's attr_accessible
  private
    def income_params
      params.require(:income).permit(:title, :user_id, :description, :type, :amount)
    end

    def declare_income
      @income = Income.find(params[:id])
    end

end

Here is my route file:

Rails.application.routes.draw do
  get 'member_content/new'

  #get 'sessions/new'  ## this is generated with rails g controller sessions new
  resources :sessions
  resources :incomes
  resources :users
  resources :abl_deductions
  get 'main/index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'
  get 'signup', to: 'users#new', as: 'signup'
  get 'login', to: 'sessions#new', as: 'login'
  get 'logout', to: 'sessions#destroy', as: 'logout'
  get 'content', to: 'member_content#new',  as: 'content'
  get 'add_income', to: 'incomes#new', as: 'add_income'
  get 'add_deduction', to: 'abl_deductions#new', as: 'add_deduction'
  get 'deductions', to: 'abl_deductions#index', as: 'deductions'

end

I am newb to rails, would it be easier for this action if I had use a scaffold with rails generate scaffold?

Upvotes: 0

Views: 965

Answers (1)

guitarman
guitarman

Reputation: 641

Let's assume your controller is called IncomesController. When you run bin/rails routes in your app folder, you should also see something like:

DELETE /incomes/:id(.:format)      incomes#destroy

To achieve this, you need to have proper routes.rb records. Easy thing to achieve standard CRUD operations over incomes is to have resources :incomes in routes.rb

You also need to have destroy method in IncomesController to perform actual destroy.

Upvotes: 1

Related Questions