简体   繁体   中英

Delete method returning error after devise logout

I'm running into a problem that I'm not exactly sure how to fix.

I have a simple to do list application with AJAX functionality on methods such as 'new', 'create', 'complete', 'delete', as well as Devise authentication.

When I first enter a new session with a User, all of these methods work without a problem. Additionally, the tasks are saved to only the user account, which is perfect.

However, when I log out of an account, and then log back in, the delete method no longer works. I receive the following error:

ActiveRecord::RecordNotFound (Couldn't find Task with 'id'=)

My tasks_controller.rb is below:

class TasksController < ApplicationController
  def index
    @task = current_user.tasks.all
  end
  def new
    @task = Task.new
    respond_to do |format|
      format.js
      format.html
    end
  end
  def create
    @task = current_user.tasks.new(task_params)
    @task.save
    respond_to do |format|
      format.html
      format.js
    end
  end
  def update
    @task = current_user.tasks.find(params[:id])
    @task.toggle :complete
    @task.save
    respond_to do |format|
      format.html
      format.js
    end
  end
  def destroy
    @task = Task.find(params[:id])
    @task.destroy
    respond_to do |format|
      format.js
      format.html
    end
  end
  private
  def task_params
    params.require(:task).permit(:id, :title, :complete)
  end
end

I'm not exactly sure how to fix this problem. Would anyone have an idea on what is going wrong here?

EDIT:

I noticed that on my index page, I have a link to destroy the user's session at the top:

<%= link_to "Log Out", destroy_user_session_path, :method => :delete %>

I'm wondering if rails is having some trouble with this as both the logout link and the delete link are referencing the same method. If so, how can I change the name of the delete method for Task?

<div class="delete"><%= link_to "X", task_path(@task), method: :delete, remote: true %></div>

What is @task referencing? It looks to me like you've set @task to a collection @task = current_user.tasks.all . Which would be why your delete method can't find a specific record to delete.

-EDIT-

Change @task in your index controller to @tasks as it is a collection. In your view, do something like:

<% @tasks.each do |task| %>
 <div><%= task.title %><div class="delete"><%= link_to "X", task_path(task), method: :delete, remote: true %></div></div>
<% end %>

The key here is that you have task_path(task) which is referencing a specific task id as opposed to task_path(@task) which is referencing a collection of tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM