Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails:仅当不再引用时,删除中的对象才有多个通过_Ruby On Rails_Has Many Through - Fatal编程技术网

Ruby on rails rails:仅当不再引用时,删除中的对象才有多个通过

Ruby on rails rails:仅当不再引用时,删除中的对象才有多个通过,ruby-on-rails,has-many-through,Ruby On Rails,Has Many Through,A员额模式: class Post < ActiveRecord::Base has_many :taggings, dependent: :destroy has_many :tags, through: :taggings 你知道我怎样才能做到这一点吗?谢谢 您正在使用插件吗?装成可标记的或类似的 如果是这样,请查看文档,因为它可能已经实现了 如果没有,则始终可以在销毁后执行回调,以计数与标记关联的元素,并在标记为“空”的情况下删除标记 例如,在您的Post模型中: clas

A员额模式:

class Post < ActiveRecord::Base
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

你知道我怎样才能做到这一点吗?谢谢

您正在使用插件吗?装成可标记的或类似的

如果是这样,请查看文档,因为它可能已经实现了

如果没有,则始终可以在销毁后执行
回调,以计数与标记关联的元素,并在标记为“空”的情况下删除标记

例如,在您的
Post
模型中:

class Post

  before_destroy :clean_up_tags

  protected

  def clean_up_tags
    tags_to_delete = Tagging.where(id: self.tag_ids).group(:tag_id).having("count(distinct taggable_id) = 1").pluck(:id)
    Tag.find(tags_to_delete).map(&:destroy)
  end

end
此方法假设您有一个方法tag_id,该方法返回与特定帖子相关联的标记,并且您的标记模型是多态的)


由于您可能有多个带有标记功能的模型,一个好的方法是将此方法打包到一个模块中,并将其包含在所有模型中,这样您就可以保持干燥。

您是否使用了任何特定的插件?(举个例子)谢谢你的回答!我知道有这样的插件存在;然而,我想手工实现这一点。我曾想过使用回调方法,但我想知道这是否是rails开箱即用的一部分。。。Rails现在并没有实现这样的事情
class Tagging < ActiveRecord::Base
  belongs_to :tag, dependent: :destroy
  belongs_to :post
  def tag_names=(names)
    self.tags = names.split(",").map{ |tag| Tag.where(name: tag.squish).first_or_create! }
  end
class Post

  before_destroy :clean_up_tags

  protected

  def clean_up_tags
    tags_to_delete = Tagging.where(id: self.tag_ids).group(:tag_id).having("count(distinct taggable_id) = 1").pluck(:id)
    Tag.find(tags_to_delete).map(&:destroy)
  end

end