Ruby on rails rails中的Sum属性
我有一个rails模型,它有一个“百分比”属性 添加新值时,我希望确保所有“百分比”的总和不大于100 在我的模型中,我有Ruby on rails rails中的Sum属性,ruby-on-rails,Ruby On Rails,我有一个rails模型,它有一个“百分比”属性 添加新值时,我希望确保所有“百分比”的总和不大于100 在我的模型中,我有 validate :sum_can_not_exceed_hundred def sum_can_not_exceed_hundred if Result.all.sum(:percentage) > 100 errors.add(:base, :sum_can_not_exceed_hundred) end end 但这不适用于添加不在数据库中且已
validate :sum_can_not_exceed_hundred
def sum_can_not_exceed_hundred
if Result.all.sum(:percentage) > 100
errors.add(:base, :sum_can_not_exceed_hundred)
end
end
但这不适用于添加不在数据库中且已保存的记录
更新:
使用Coderhs的提示,以下内容似乎有效
if Result.where.not(id: self.id).sum(:percentage_share) + self.percentage_share > 100
errors.add(:base, :sum_can_not_exceed_hundred)
end
由于您的表是新的,因此在Result.all上不可用。尝试这样修改代码
validate :sum_can_not_exceed_hundred
def sum_can_not_exceed_hundred
sum = if self.id
Result.all.sum(:percentage)
else
self.percentage + Result.all.sum(:percentage)
end
errors.add(:base, :sum_can_not_exceed_hundred) if sum > 100
end
end
但这对编辑不起作用,因为Result.all包括正在编辑的行,对吗?最简单的修复方法是添加一个条件,以检查其是否在创建或更新时发生。您可以在##before#create:check#percentage上调用一个方法