好滑軌的驗證輔助回報,我已經有了一個模型,這個簡化版本(的Rails 3.2.13):製作假
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
回調未被調用。
我不知道怎麼去使用此相同的行爲的Rails內置的驗證輔助,這是我試了一下:
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'當作另一個驗證器。查看我的編輯瞭解更多信息。 –
再一次,我很感激答覆。我編輯了擴展示例的問題(我想我不應該簡化它開始),以顯示*爲什麼*我希望驗證一旦失敗就停止。正如你所看到的,我有一個'after_validation'方法,我希望一旦所有的驗證都通過並且沒有錯誤就運行。我使用驗證助手最接近的是'after_validation:update_users_balance,如果:: all_valid'其中'def all_valid; self.errors.empty ?; end'。然而,由於某些原因,**保存**新的@ @轉移,即使它是無效的。 :/ – lllllll