开发者

How can I delete the tag from the tag list of the act_as_taggable plugin?

开发者 https://www.devze.com 2022-12-17 06:29 出处:网络
I have tried to destroy tags from the given code but it\'s not working. How can it be accomplished? 开发者_运维知识库 @tag = Tag.find_by_name(params[:name])

I have tried to destroy tags from the given code but it's not working. How can it be accomplished?

开发者_运维知识库 @tag = Tag.find_by_name(params[:name])
  @tag.destroy
  render :update do |page|
    page[:divtag].innerHTML = render :partial => "controls/tag_list"
  end


The example you provided seems broken. Normally you have a list of tags belonging to a Model (lets say a User model). Then you could call something like this:

# Find a user
@user = User.find_by_name("Bobby")
# Show available tags
@user.tag_list # => ["awesome", "slick", "hefty"] as TagList
# Remove the "slick" tag
@user.tag_list.remove("slick")
# Store change
@user.save

For more information look at the acts-as-taggable-on readme (unfortunately, removing tags is not explained).


ActsAsTaggableOn doesn't have a good way to do this built in (that I can find). Here's how I did it:

First, find the tags you want to delete. This should be an Array or ActsAsTaggableOn::Tag::ActiveRecord_AssociationRelation

If you've implemented acts_as_tagger:

tags = @user.owned_tags.where(name: my_array_of_tag_names)

If you want to find tags by all owners (or aren't using acts_as_tagger):

tags = ActsAsTaggableOn::Tag.where(name: my_array_of_tag_names)

Then you loop through the tags, find all the taggings and delete them, and then finally delete the tag. (Note that destroy won't work in this case)

tags.each do |tag|
  ActsAsTaggableOn::Tagging.where(tag_id: tag.id).delete_all
  tag.delete
end


If you're interested in deleting all the tags, you can send delete_all to the relation.

Short example

> resource.grades.delete_all
> resource.reload
> resource.grades
=> []

Long example

> resource.grades
=> [#<ActsAsTaggableOn::Tag id: 336486, name: "Kindergarten", context: nil, sort: 0>,
 #<ActsAsTaggableOn::Tag id: 336506, name: "Pre-K", context: nil, sort: 0>]
> resource.grades.delete_all
   (0.3ms)  BEGIN
  SQL (0.5ms)  DELETE FROM `taggings` WHERE `taggings`.`taggable_id` = 984643 AND `taggings`.`taggable_type` = 'Resource' AND `taggings`.`tag_id` IN (336486, 336506) AND (taggings.context = 'grades')
   (0.2ms)  COMMIT
=> [#<ActsAsTaggableOn::Tag id: 336486, name: "Kindergarten", context: nil, sort: 0>,
 #<ActsAsTaggableOn::Tag id: 336506, name: "Pre-K", context: nil, sort: 0>]
> resource.reload
  Resource Load (0.6ms)  SELECT `resources`.* FROM `resources` WHERE `resources`.`id` = 984643 LIMIT 1
=> #<Resource id: ...>
> resource.grades
  ActsAsTaggableOn::Tag Load (0.6ms)  SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 984643 AND `taggings`.`taggable_type` = 'Resource' AND (taggings.context = 'grades')
=> []
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号