2012-11-07 5 views
0

내 모델 (경매)에 두 가지 속성 (시간 및 일)이 있습니다. 시간과 업무의 결합으로 비즈니스 논리를가집니다. 내가 시간과 일 양쪽 모두 0이 될 수 없도록, 검증에 내 비즈니스 로직을 통합하려는은 속성 조합의 유효성을 확인합니다.

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 } 

예를

auction duration = days*24 + hours 

를 들어 나는 또한 시간과 일에 대한 몇 가지 기본적인 검증 있습니다. 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 

답변

0

그래서 내 최종 솔루션은 @의 rharrison33의 확장이었다

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

더 많은 정보는에서이다 :

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 
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 
+0

일 및 시간의 존재는 유효하지 않습니까? 나는 그것이되어야한다고 생각한다 : if! (days = 0 && hours = 0) – tir38

+0

이것은 작동 할 것이다. 시도 해봐. 나는이 조건이 사실로 평가되기 위해서는 일과 시간이 모두 0이어야한다고 생각합니다. 내가 사용했던 대부분의 언어에서, 변수가 0이면 거짓으로 평가됩니다. 또한 변수가 0이 아닌 경우 true로 평가됩니다. 하지만 ...이 언어에 대해서는 잘 모르겠습니다. – rharrison33

+0

레일스가 반드시 이러한 vaildation을 순서대로 수행하지는 않습니까? 그것은 일의 유효성을 검사하거나 시간을 확인하기 전에 days_and_hours의 유효성을 검사 할 수 있습니까? – tir38

0

당신은 numericality 검사기를 사용하여 0보다 큰 값을 확인할 수 있습니다 : http://guides.rubyonrails.org/active_record_validations_callbacks.html#numericality

+0

하지만 다른 속성 (auction_duration)을 사용하면이 문제를 피하려고합니다. – tir38

+0

다른 속성보다는 auction_duration이라는 메서드를 모델에 포함시킬 수 있다고 생각했습니다. 이 'days * 24 + hours' 계산을 자주 사용하기 때문에 메서드에서 한 번 생성하여 모든 곳에서 사용하는 것이 좋습니다 – Averenix

관련 문제