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
此功能将工作,但我无法访问标签。 如何访问被删除食谱的标签?
感谢您的详细解释! –