2016-11-29 41 views
1

我有一个配方门户,这些配方可以有标签。Rails 4:在before_destroy回调中访问变量

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 

此功能将工作,但我无法访问标签。 如何访问被删除食谱的标签?

回答

2

您正在访问的配方的标签,但你是不是前的实际破坏配方对象的执行看到任何东西becase的dependant_destroy

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

因为你不想破坏标签每次你摧毁一个配方,但只有当是唯一一个你应该删除您dependant_destroy,并放置在一个after_destroy逻辑,因此产生的代码将是:

class Recipe < ApplicationRecord 
    has_many :taggings 
    has_many :tags, through: :taggings 

    after_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 
+0

感谢您的详细解释! –