음과 레일의 검증 도우미 반환합니다 (레일 3.2.13) :내가 모델이 <em>단순화 된 버전</em>있어, 거짓
class Transfer < ActiveRecord::Base
attr_accessible :from,:to,:total
validates_presence_of :from,:to,:total
before_validation :positive_numbers, on: :create
before_validation :check_enough_balance, on: :create
after_validation :update_balances
private
def positive_numbers
unless self.total>0
errors.add(:total,"should be greater than 0")
return false
end
end
def check_enough_balance
@sender=User.find(self.from)
@receiver=User.find(self.to)
unless @sender.enough_balance(self.total)
errors.add(:base,"Not enough credit")
return false
end
end
def update_balances
@sender.balance -= self.total
@receiver.balance += self.total
@sender.save
@receiver.save
end
def another_action
puts 'does something'
end
end
total<0
는, 인스턴스가 false
으로 반환 할 때마다, errors
배열이 제대로 채워지고 another_action
콜백이 호출되지 않습니다.
레일에 내장 된 검증 헬퍼, 이것은 내가 그것을 시도하는 방법이다 : 유효성 검증 도우미하지 않기 때문에,이 경우 그러나
class Transfer < ActiveRecord::Base
attr_accessible :from,:to,:total
validates_presence_of :from,:to,:total
validates_numericality_of :total, greater_than: 0
before_validation :check_enough_balance, on: :create
after_validation :update_balances
private
def check_enough_balance
@sender=User.find(self.from)
@receiver=User.find(self.to)
unless @sender.enough_balance(self.total)
errors.add(:base,"Not enough credit")
return false
end
end
def update_balances
@sender.balance -= self.total
@receiver.balance += self.total
@sender.save
@receiver.save
end
end
class User<ActiveRecord::Base
attr_accessible :username
validates_presence_of :username, :balance
def enough_balance(amount)
self.balance >= amount
end
end
을 return false
다음 사용자 지정 유효성 검사 check_enough_balance
이 호출됩니다. 정확히 동일하게 작동하고 싶습니다. 유효성 검사 도우미를 사용하는 것이 다소 우아하고 간결합니다.
합니다. 그러나 ** 유효성 검사를하기 전에 콜백이 필요하다는 것을 잊었습니다. 예제를 편집하여 이전의'another_action'이'check_enough_balance'가되어 충분한 신용을 확인합니다. 나는 그 대답에 감사한다. – lllllll
@ vint-i-vuit 나는 당신의 예제에서'check_enough_balance'를 다른 validator로 취급해야한다고 생각합니다. 자세한 내용은 내 편집을 참조하십시오. –
다시 한 번 답변 드리겠습니다. 나는 예제를 확장하는 질문을 편집했다. (필자는 그것을 단순화해서는 안된다.) 왜 * 왜 * 하나가 실패하자마자 유효성 검사를 중단하기를 원한다. 당신이 볼 수 있듯이 모든 검증이 오류없이 통과하면 실행되기를 원하는'after_validation' 메서드가 있습니다. 유효성 확인 도우미를 사용하여 얻은 가장 가까운 것은'after_validation : update_users_balance, if : : all_valid'입니다. 여기서'def all_valid; self.errors.empty ?; 끝 '. 그러나 이것은 어떤 이유로 ** ** 새로운'@ transfer'를 무효화하더라도 ** 저장합니다. :/ – lllllll