我试图从给定代码中销毁标签,但它无法正常工作。如何实现?
@tag = Tag.find_by_name(params[:name])
@tag.destroy
render :update do |page|
page[:divtag].innerHTML = render :partial => "controls/tag_list"
end
答案 0 :(得分:13)
您提供的示例似乎已损坏。通常,您有一个属于模型的标签列表(比如用户模型)。然后你可以这样打电话:
# 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
有关详细信息,请查看acts-as-taggable-on readme(遗憾的是,未解释删除标记)。
答案 1 :(得分:3)
ActsAsTaggableOn没有很好的方法来做这个(我能找到)。我是这样做的:
首先,找到要删除的标签。这应该是Array
或ActsAsTaggableOn::Tag::ActiveRecord_AssociationRelation
如果您已实施acts_as_tagger
:
tags = @user.owned_tags.where(name: my_array_of_tag_names)
如果您想查找所有所有者的标签(或未使用acts_as_tagger
):
tags = ActsAsTaggableOn::Tag.where(name: my_array_of_tag_names)
然后,您遍历标记,找到所有标记并delete
,然后最后delete
标记。 (请注意destroy
在这种情况下不起作用)
tags.each do |tag|
ActsAsTaggableOn::Tagging.where(tag_id: tag.id).delete_all
tag.delete
end
答案 2 :(得分:2)
如果您对删除所有标记感兴趣,可以将delete_all
发送给该关系。
简短示例
> resource.grades.delete_all
> resource.reload
> resource.grades
=> []
长示例
> 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')
=> []