dgresh24
dgresh24

Reputation: 77

NoMethodError (undefined method `destroy' for nil:NilClass):

I am having a problem deleting clients I have created in rails. I am using rails 6.0

"undefined method `destroy' for nil:NilClass"

Controller:

    class ClientsController < ApplicationController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

 def destroy_multiple
@client.destroy(params[:client_ids])
respond_to do |format|
  format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' }
  format.json { head :no_content }
 end
end

View:

<div class="container">
  <div class="table-responsive">
    <%= form_tag destroy_multiple_clients_path, method: :delete do %>

<table class="table table-hover">
  <thead>
    <tr class="table-secondary">
      <th scope="col" ><input type="checkbox"></th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone number</th>
      <th>Client Type</th>
      <th>Nickname</th>
    </tr>
  </thead>

  <tbody>
    <% @clients.each do |client| %>
      <tr>
        <td><%= check_box_tag "client_ids[]", client.id %></td>
        <td><%= link_to client.name, client, :class => "clientname" %></td>
        <td><%= client.email %></td>
        <td><%= client.phone_number %></td>
        <td><%= client.client_type %></td>
        <td><%= client.nickname %></td>
    <% end %>
  </tbody>
</table>
</div>

 <hr class="featurette-divider">
   <%= submit_tag "Delete selected", :class => 'btn btn-primary btn-xs' %>

Console:

 Parameters: {"authenticity_token"=>".................==", "client_ids"=>["11"], "commit"=>"Delete selected"}
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.0ms | Allocations: 1019)



NoMethodError (undefined method `destroy' for nil:NilClass):

app/controllers/clients_controller.rb:65:in `destroy_multiple'

Not sure what I am missing here? How can I pass the ID that shows up in the console to the controller? The examples online show what I am doing but it isn't working for me.

Upvotes: 2

Views: 1361

Answers (1)

jamesc
jamesc

Reputation: 12837

You are using an instance variable that is nil. The destroy method should use the class method e.g. instead of

@client.destroy(params[:client_ids])

you could try

Client.destroy(params[:client_ids])

with regards to your question

How can I pass the ID that shows up in the console to the controller? You are already doing that as evidenced in your stack trace

Parameters: {"authenticity_token"=>".................==", "client_ids"=>["11"], "commit"=>"Delete selected"}

You can clearly see the client_ids parameter is being passed an array, hence the square brackets [] containing a single element with the value of 11 hence the =>["11"]

Upvotes: 2

Related Questions