0

我的模型(拍卖)中有两个属性(小时和天)。我对小时和天的组合有业务逻辑。例如

auction duration = days*24 + hours

我也有几个小时和天的一些基本验证:

class Auction < ActiveRecord::Base
  validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
  validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }

我想将我的业务逻辑合并到验证中,这样小时和天不能都为零。有没有办法通过 ActiveRecord 验证来做到这一点?我知道在没有 AR 验证的情况下还有其他方法可以做到这一点。现在我正在创建我的模型的一个新实例。验证上述日期和时间。然后我有一个模型方法,它“手动”进行验证,如果实例没有通过,则删除它。我知道这不是最好的方法

  def compute_end_time
    # assumes that days and hours are already valid
    time = self.days*24 + self.hours

    if time > 1
      self.end_time =  time.hours.from_now.utc
      self.save

    else
      # Auction duration too short (i.e. zero)
      self.delete
    end
  end
4

3 回答 3

2

您需要编写一个类似这样的私有验证函数。

class Auction < ActiveRecord::Base
   validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
   validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }

   validate :days_and_hours

   private

   def days_and_hours
     if !(days && hours)
     errors.add_to_base("Days and hours can not be zero. Thank you.")
   end
 end
end
于 2012-11-07T03:15:01.830 回答
0

您可以使用数值验证器检查大于 0 的值:

validates :auction_duration, :numericality => { :greater_than => 0 }

更多信息位于: http: //guides.rubyonrails.org/active_record_validations_callbacks.html#numericality

于 2012-11-07T03:24:53.893 回答
0

所以我的最终解决方案是扩展@rharrison33:

  validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
  validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
  validate :days_and_hours

def days_and_hours
    # It may not validate days and hours separately before validating days_and_hours,
    # so I need to make sure that days and hours are both not NIL before trying to compute 'time'
    # I also only want to compute end_time if it has not been computed yet
    if (!self.days.nil? && !self.hours.nil?)

      if (self.end_time.nil?) # if end_time has not yet been computed

        if (self.days == 0 && self.hours == 0)
          self.errors[:base] << "Days and hours can not be zero."
        else
          time =  self.hours  + self.days*24
          self.end_time = time.minutes.from_now.utc
          self.setStatus # validate status after end time is set
        end
      end
    end
  end
于 2013-02-27T22:13:35.883 回答