0

The problem is the code below

<%= button_to t('.delete'), @post, :method => :delete, :class => :destroy %>

My Post model has many relations that are dependent on delete. However, the code above will only remove the post, leaving its relations intact. The problem is that methods delete and destroy are different in that method delete doesn't instantiate the object.

So I need to use "destroy" instead of "delete" my post.

<%= button_to t('.delete'), @post, :method => :destroy %> gives me routing error.

No route matches [POST] "/posts/2"

<%= button_to t('.delete'), @post, Post.destroy(@post) %> deletes the post without clicking the button.

Could anyone help me with this?

UPDATE:

application.js

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap-modal
//= require bootstrap-typeahead
//= require_tree .

rake routes

DELETE (/:locale)/posts/:id(.:format)                        posts#destroy

Post model

has_many :tag_links, :dependent => :destroy
has_many :tags, :through => :tag_links

Tag model

has_many :tag_links, :dependent => :destroy
has_many :posts, :through => :tag_links

Problem: When I delete a post, all the tag_links are destroyed but tags still exist.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Maximus S
  • 10,759
  • 19
  • 75
  • 154

1 Answers1

0

:method => :delete means the HTTP METHOD DELETE, nothing related with the delete method of active record.

You need to check your code of your models, have you missed the :dependent => :destroy options of the relations?

For example, if the post has many comments, then it should be:

has_many :comments, :dependent => :destroy

Of course, in your controller, you need to use @post.destroy instead of @post.delete.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • I see. Then I don't understand why my tags still persist when the related post is deleted. Could you check my models and see if there's a problem with my setting? – Maximus S Dec 09 '12 at 05:02
  • 1
    @MaximusS Why should tags be deleted? post and tag are many to many relations, so when a post is deleted, only related tag_list should be deleted, the tag should not be deleted, other posts may also reference the tag. – xdazz Dec 09 '12 at 05:10
  • but if the deleted post had a unique tag, which none of the other posts had reference to, shouldn't the tag be removed? – Maximus S Dec 09 '12 at 05:12
  • @MaximusS No, it should not be removed, if you want to, you need to want to write your own callback methods, check whether the tag should be removed. – xdazz Dec 09 '12 at 05:14