I am trying to simply create a button that will delete a contact from a list of contacts.
At the moment I have the following setup:
Contacts Controller
def destroy
@user.contacts.delete(params[:contact])
@contact.delete
end
View
<tbody>
<% @contacts.each do |contact| %>
<tr>
<td><%= contact.name %></td>
<td><%= contact.company %></td>
<td><%= contact.email %></td>
<td><%= contact.phone %></td>
<td><%= contact.mobile %></td>
<td><%= button_to 'Delete', contact, :method => :delete %></td>
</tr>
<% end %>
Routes
controller :contact do
get "newcontact" => "contact#new"
get "index" => "contact#index"
delete "delete" => "contact#destroy"
end
I have read online that using button_to is the preferred method but at the moment I am getting the following error:
undefined method `contacts' for nil:NilClass
It would be great to get any feedback that might help me fix this.
Thanks in advance
Tom
For anyone looking for the final answer on this it was
def destroy
contact = current_user.contacts.find(params[:id])
contact.destroy
redirect_to index_path
end
In my controller and the following in my view
<%= button_to 'Delete', contact, :method => :delete %>
Thanks
Tom
If you are goin to use @user you need to set
@userin your delete method or else it will be nil – hence the error messageThe other issue is that the id of the contact is
params[:id]and notparams[:contact]I’d just do
You definitely want to be deleting the contact via the user or else people can delete other users’ contacts. This deletes the contact and removes it from the association – you don’t need to do anything else