Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails中的Sum属性_Ruby On Rails - Fatal编程技术网

Ruby on rails rails中的Sum属性

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 但这不适用于添加不在数据库中且已

我有一个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
但这不适用于添加不在数据库中且已保存的记录

更新: 使用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上调用一个方法