这是我的代码:
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
答案 0 :(得分:0)
这有效:
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