Reputation: 917
In Tasks controller I have action:
def destroy_all
current_user.tasks.destroy
redirect_to root_path
end
My db schema looks like below:
create_table "tasks", force: true do |t|
t.string "content"
t.boolean "done"
t.datetime "created_at"
t.datetime "updated_at"
t.string "users_id"
end
And I have relation: Tasks belongs_to User and User has_many Tasks.
By action destory_all
I want to destroy all current user's tasks.
But when I click:
<%= link_to "delete all", { controller: 'tasks', action: 'destroy_all'}, method: 'delete' %>
Nothing happen. User still have all his tasks.
Log from server console:
Started DELETE "/tasks/destroy_all" for 127.0.0.1 at 2014-10-04 23:29:27 +0200
Processing by TasksController#destroy_all as HTML
Parameters: {"authenticity_token"=>"fVPDi6bczNXlfhjCDI4pJhMUm3cjv6TN1Ny/ulUO4YQ="}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC LIMIT 1
Redirected to http://localhost:3000/
Completed 302 Found in 31ms (ActiveRecord: 0.2ms)
Started GET "/" for 127.0.0.1 at 2014-10-04 23:29:27 +0200
Processing by PagesController#home as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC LIMIT 1
Task Load (0.1ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."done" = 'f' AND "tasks"."user_id" = 2
Rendered tasks/index.html.erb within layouts/application (2.4ms)
Rendered layouts/_userbar.html.erb (0.2ms)
Rendered layouts/_menu.html.erb (0.1ms)
Completed 200 OK in 46ms (Views: 44.3ms | ActiveRecord: 0.3ms)
And routes.rb file
resources :tasks do
collection do
delete :destroy_all
end
end
EDIT: I updated log and link_to method and I added routes.rb file.
Upvotes: 1
Views: 68
Reputation: 23307
First, your task table needs the field "user_id", not "users_id". This will probably fix your problem right away.
However, you're missing the power of has_many! Just do this:
current_user.tasks.destroy_all
Calling "current_user.tasks" gets a list of the user's task for you, and you can then call "destroy" on them as I did above. This is cleaner and easier to read.
I hope this helps!
Upvotes: 4
Reputation: 477
According to your schema, users_id
is a String
which might be "1"
or "2"
. But the current_user.id
is Integer
which might be 1
or 2
.
In this case, you will find nothing in your ActiveRecord because it queries for items that id is a string, which you actually send an integer.
Thus try:
Task.destroy_all(users_id: current_user.id.to_s)
to match the type.
==============================
However, your structure is complicated and it will be hard to maintain in the future. I suggest you do the following:
Task
model, change users_id
to user_id
because it only belongs to a single user.user_id
to integer because it is id
, and logically it only contains numeric value.has_many
and write something like current_user.tasks.delete_all
to keep your code clean and more readable.Upvotes: 0