【问题标题】:Rails validation works on create, but not on updateRails 验证适用于创建,但不适用于更新
【发布时间】:2015-10-22 17:38:26
【问题描述】:

这是我的代码:

validate :ranges_overlap

def ranges_overlap
    Commission.where("commission_type = ?",self.commission_type).each do |c|
        for i in self.start_range.to_i..self.end_range.to_i do
            if i >= c.start_range and i <= c.end_range
                self.errors.add(:start_range, "Range overlaps existing range: #{c.start_range} - #{c.end_range}") 
                break
            end
        end
    end     
end

它在创建时效果很好,但在更新时,它不会忽略自己。例如,如果我有一个从 0 到 100 的范围,并且想将其更新为 1 到 100,它会失败,因为它本身与自身重叠。

所以,我将代码更改为:

Commission.where("commission_type = ?",self.commission_type).where("id NOT IN (?)",self.id).each do |c|

所以,它允许我更新,但它有效地禁用了验证,使用此代码我可以重叠创建和更新的任何范围,就好像我根本没有进行验证一样。

我绝对不知道一些简单的事情。我的验证做错了什么?

谢谢

编辑:更新控制器上的操作

def update
    respond_to do |format|
      if @commission.update(commission_params)
        format.html { redirect_to commissions_path, notice: 'Commission updated successfully' }
        format.json { render :show, status: :ok, location: commissions_path }
      else
        format.html { render :edit }
        format.json { render json: @commission.errors, status: :unprocessable_entity }
      end
    end
end

【问题讨论】:

  • 请显示您的控制器更新操作
  • 试试这个Commission.where("id NOT IN (?) AND commission_type = ?",self.id, self.commission_type).each do |c|

标签: ruby-on-rails validation


【解决方案1】:

这行得通:

def ranges_overlap
    Commission.where("commission_type = ?",self.commission_type).each do |c|
        unless self.id == c.id
            for i in self.start_range.to_i..self.end_range.to_i do
                if i >= c.start_range and i <= c.end_range
                    self.errors.add(:start_range, "Range overlaps existing range: #{c.start_range} - #{c.end_range}") 
                    break
                end
            end
        end 
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2016-11-11
    • 2014-08-16
    • 2017-10-29
    • 2018-03-14
    相关资源
    最近更新 更多