【问题标题】:Rails 4 - Custom Validation ErrorRails 4 - 自定义验证错误
【发布时间】:2016-05-02 11:56:34
【问题描述】:

这是我的模型 -

class Leave < ActiveRecord::Base
belongs_to :staff
validates :staff, :leave_type, :start_date, :end_date, :number_of_days, :approved_by, presence: true
enum leave_type: {Medical: 0, Annual: 1, Urgent: 3, "Birth Leave": 4}
validate :check_leave, :if => "self.number_of_days.present?"




protected

def check_leave
  if self.leave_type = 0
    if ( self.number_of_days + LeaveAllocation.last.medical_leave_counter ) > LeaveAllocation.last.medical_leave
      self.errors.add(:number_of_days, "Days exceeded the limit")
    end
  end
  if self.leave_type = 1
    if ( self.number_of_days + LeaveAllocation.last.annual_leave_counter ) > LeaveAllocation.last.annual_leave
      self.errors.add(:number_of_days, "Days exceeded the limit")
    end
  end

end

end

当我尝试运行验证时,它似乎只检查第一个“0”,即使我将选择更改为“1”。任何帮助,将不胜感激!谢谢

【问题讨论】:

  • 在创建和更新时,number_of_days 是字段名(整数)
  • 你能发布完整的模型类吗? @肖恩林
  • 更新完整模型
  • :if =&gt; "self.number_of_days.present?" 为什么这里需要双引号? @肖恩林
  • 单人还是双人都没区别。

标签: ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

在if条件下改为==。

self.leave_type == 0 and
self.leave_type == 1

【讨论】:

  • 更改为 == 后将无法验证。如果我使用 =,它会验证但只有第一个......
  • 把这一行改成这样validate :check_leave, if: -&gt; { self.number_of_days.present? }
  • 还是一样..只验证第一步为“0”
猜你喜欢
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多