我有2個模型。 User
和Want
。 A User
has_many:
Want
s。Rails - 在定製驗證過程中'不能使用默認proc轉儲散列'
Want
模型除了user_id
之外還有一個屬性,那就是name
。
我在Want
模型編寫自定義驗證,以便用戶無法提交到創建2個具有相同名稱的希望:
validate :existing_want
private
def existing_want
return unless errors.blank?
errors.add(:existing_want, "you already want that") if user.already_wants? name
end
的already_wants?
方法是在用戶模式:
def already_wants? want_name
does_want_already = false
self.wants.each { |w| does_want_already = true if w.name == want_name }
does_want_already
end
驗證規格在我的模型測試中通過,但我的功能測試失敗,當我嘗試並提交create
動作WantsController
:
def create
@want = current_user.wants.build(params[:want])
if @want.save
flash[:success] = "success!"
redirect_to user_account_path current_user.username
else
flash[:validation] = @want.errors
redirect_to user_account_path current_user.username
end
end
的錯誤,我得到:不能使用默認PROC
沒有堆棧跟蹤,導致我的代碼傾倒哈希值。
我已經縮小的問題降到這一行:
self.wants.each { |w| does_want_already = true if w.name == want_name }
,如果我只是返回true
不管錯誤顯示在我看來,我想。
我不明白?怎麼了?爲什麼它如此神祕?
謝謝。
是什麼一味以一個ActiveRecord對象? http://stackoverflow.com/q/6391855/479863 –