Rails 4:在before_destroy回调中访问变量

时间:2016-11-29 21:58:43

标签: ruby-on-rails ruby ruby-on-rails-4 callback

我有一个食谱门户,这些食谱可以有标签。

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

class Tag < ActiveRecord::Base
    has_many :taggings, dependent: :destroy
    has_many :recipes, through: :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :recipe
end

...当我删除食谱时,如果要删除的食谱是唯一具有此标签的食谱,我想删除标签

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

    before_destroy :remove_tags

    private

    # I need to pass an individual recipe
    def remove_tags
        if self.tags.present?
            self.tags.each do |tag|
                Recipe.tagged_with(tag).length == 1 ? tag.delete : next
                # tagged_with() returns recipes with the given tag name
            end
        end
    end
end

此功能可以使用但我无法访问标签。 如何访问要删除的食谱的标签?

1 个答案:

答案 0 :(得分:2)

您正在访问食谱的标签,但是您没有看到任何内容,因为{<1}}执行之前实际销毁配方对象。

如果仔细检查启动的查询,您将在回调之前看到dependant_destroy被执行,因此当您尝试访问配方的标签时,它会返回一个空数组。

因为您不想在每次销毁配方时销毁标签,但只有在唯一的时候才应删除DELETE FROM "taggings" . . .并将逻辑放在dependant_destroy中,以便生成代码将是:

after_destroy