我想为我的帖子创建一个特殊的类别,这是默认的并且具有三个不同的特征:
- 它默认分配给每个创建的帖子
- 在其父类别被销毁时分配给从属帖子
- 防止任何人删除
所以第一点很容易实现,这里就不重点说了
第二点比较费解。我猜像这样的东西应该进入我的类别模型:
before_destroy :move_dependent_posts
def move_dependent_posts
#no idea what goes here
end
与第三点相同的问题:我必须检查,如果要删除的类别的 ID 为 1,然后抛出错误?
before_destroy :protect_default_category
def protect_default_category
return false if category.id(5) #won't work, of course
end
最佳答案
第 2 点:
before_destroy :move_dependent_posts
def move_dependent_posts
default_category = Category.default_category # find default category here
posts.each { |post| post.update_attribute(:category, default_category) }
end
第 3 点:
before_destroy :protect_default_category
def protect_default_category
throw "Default category can't be deleted" if id == 1
end
关于ruby-on-rails - Rails - 创建 protected 默认类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806248/