ruby on rails - I can't cope with custom action in controller -
ruby on rails - I can't cope with custom action in controller -
in tasks controller have action:
def destroy_all current_user.tasks.destroy redirect_to root_path end
my db schema looks below:
create_table "tasks", force: true |t| t.string "content" t.boolean "done" t.datetime "created_at" t.datetime "updated_at" t.string "users_id" end
and have relation: tasks belongs_to user , user has_many tasks. action destory_all
want destroy current user's tasks.
but when click:
<%= link_to "delete all", { controller: 'tasks', action: 'destroy_all'}, method: 'delete' %>
nothing happen. user still have tasks.
log server console:
started delete "/tasks/destroy_all" 127.0.0.1 @ 2014-10-04 23:29:27 +0200 processing taskscontroller#destroy_all html parameters: {"authenticity_token"=>"fvpdi6bcznxlfhjcdi4pjhmum3cjv6tn1ny/uluo4yq="} user load (0.2ms) select "users".* "users" "users"."id" = 2 order "users"."id" asc limit 1 redirected http://localhost:3000/ completed 302 found in 31ms (activerecord: 0.2ms) started "/" 127.0.0.1 @ 2014-10-04 23:29:27 +0200 processing pagescontroller#home html user load (0.2ms) select "users".* "users" "users"."id" = 2 order "users"."id" asc limit 1 task load (0.1ms) select "tasks".* "tasks" "tasks"."done" = 'f' , "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 collection delete :destroy_all end end
edit: updated log , link_to method , added routes.rb file.
first, task table needs field "user_id", not "users_id". prepare problem right away.
however, you're missing powerfulness of has_many! this:
current_user.tasks.destroy_all
calling "current_user.tasks" gets list of user's task you, , can phone call "destroy" on them did above. cleaner , easier read.
i hope helps!
ruby-on-rails ruby-on-rails-4
Comments
Post a Comment