"unless articles.count == 0"
过滤器中的条件before_destroy
不起作用。
有没有人有类似的问题?
class Category
has_many :articles
before_destroy :ensure_has_no_articles
private
def ensure_has_no_articles
unless articles.count == 0
errors[:base] << "cannot delete category that has articles"
return false
end
end
答案 0 :(得分:0)
尝试:
class Category
has_many :articles
before_destroy :ensure_has_no_articles
private
def ensure_has_no_articles
return true if articles.count == 0
errors[:base] << "cannot delete category that has articles"
return false
end
<强>更新强>
class Category < ActiveRecord::Base
has_many :articles, :dependent => :restrict_with_error
答案 1 :(得分:0)
正如对类似问题的回答所述:https://stackoverflow.com/a/5520381/580346如果你想要调用destroy,你需要返回true
。您的ensure_has_no_articles
始终返回false
。 @ sunil-b-n提供的答案可以帮到你。
您可能也喜欢:Validate Before Destroy
答案 2 :(得分:0)
此方法已根据this rails issue弃用
解决此问题的最佳方法
class Category
has_many :articles
before_destroy :ensure_has_no_articles
private
def ensure_has_no_articles
unless articles.count == 0
errors[:base] << "cannot delete category that has articles"
throw(:abort)
end
end