ruby on rails link_to delete method not working

stergosz picture stergosz · Oct 21, 2012 · Viewed 22.3k times · Source

I am trying to delete a post using the code below:

<%= link_to 'Destroy', post, :method => :delete, :onclick => "return confirm('Are you sure you want to delete this post?')" %>

which does not work... it simply redirects me back to the post (posts/:id}

however, if i use the following code it works

<%= button_to 'Destroy', post, method: :delete, :onclick => "return confirm('Are you sure you want to delete this post?')" %>

is it possible to make link_to behave as button_to in this case?

EDIT: destroy controller function

  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  end

log when i click the destroy button:

Started GET "/posts/14" for 127.0.0.1 at 2012-10-21 15:38:28 +0300
Processing by PostsController#show as HTML
  Parameters: {"id"=>"14"}
  Post Load (0.4ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 14 LIMIT 1
  Rendered posts/show.html.erb within layouts/application (0.6ms)
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Completed 200 OK in 7ms (Views: 5.4ms | ActiveRecord: 0.8ms)
[2012-10-21 15:38:28] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

routes:

  devise_for :users

  resources :users

  resources :posts

  match '/about' => 'about#index'

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  root :to => 'index#index'

  # See how all your routes lay out with "rake routes"

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id))(.:format)'
  match '*a', :to => 'error#routing'

Answer

harsh4u picture harsh4u · May 31, 2013

You must be add

//= require jquery
//= require jquery_ujs

in javascripts/application.js file

second, check in layout file,

javascript_include_tag "application"

is include or not?

Hope this help.