我有一个看起来像这样的模型:
class thing < ActiveRecord::Base
has_many :bobbles
validate :has_two_bobbles
def has_two_bobbles
unless self.bobbles.size == 2
errors.add(:bobbles, "Need two bobbles")
end
end
end
从表单更新时,我遇到了麻烦。如果我删除了一个bobble并在同一个提交中添加了一个bobble,当我点击self.bobbles.size时,我得到3而不是2.是否有任何地方限制self.bobbles仅返回未计划删除的记录?
我知道在控制器中您可以访问参数中的_destroy,但是模型级别是否有任何内容表明记录是否会被删除?
答案 0 :(得分:2)
当回复.marked_for_destruction?
class thing < ActiveRecord::Base
has_many :bobbles
validate :has_two_bobbles
def has_two_bobbles
unless self.bobbles.select {|t| !t.marked_for_destruction?}.size == 2
errors.add(:bobbles, "Need two bobbles")
end
end
end