2013-04-08 27 views
1

我正在使用validates_existence_of gem。除非我想允許我的外鍵爲零,否則它運行良好。RoR - Validates_existence_of無零外鍵不起作用

這裏是我的用戶和項目模型。項目屬於用戶和貢獻者(貢獻者也是用戶),但貢獻者可以爲零。

這裏是我的用戶模型:

class User < ActiveRecord::Base 
    attr_accessible :first_name, :last_name 
    has_many :projects, :dependent => :destroy 
    has_many :user_trimester_statuses, :dependent => :destroy 
end 

這裏是我的項目模型:

class Project < ActiveRecord::Base 
    attr_accessible :added, :amount, :contributor_id, :label, :ref, :trimester_id, :user_id 
    belongs_to :user 
    belongs_to :contributor, :class_name => 'User' 
    belongs_to :trimester 
    validates :user, :existence => { :both => false } 
    validates :trimester, :existence => { :both => false } 
    validates :contributor, :existence => { :allow_nil => true, :both => false } 
end 

當我嘗試添加一個新的項目,我有一個錯誤,如果USER_ID或trimester_id場是空白或無效的。但對於contributor_id字段,如果該字段無效,則不會引發錯誤。它通過任何方式(有效,無效或無)。

我在做什麼錯? 我使用ruby 2.0.0p0和rails 3.2.13。

回答

2

看起來在項目中有一個關於此的開放性錯誤。

https://github.com/perfectline/validates_existence/issues/15

您可能需要寫一個簡單的自定義驗證這種情況,直到此得到固定。 (或挖掘,看看你是否可以自己修復這個問題)

更新: 我剛克隆了項目,並寫了一個測試,看看問題是什麼。看起來,當你添加allow_nil時,存在驗證器根本不會被調用。 我不確定這是爲什麼,但在此期間,您可以通過使用proc以簡單的方式解決該錯誤。的 代替

validates :contributor, :existence => { :allow_nil => true, :both => false } 

這將完成這項工作

validates_existence_of :contributor, :unless => Proc.new { |obj| obj.contributor_id.blank? } 

我能夠證明,在我的測試案例。 (我用'validates_existence_of'方法,而不是'驗證',因爲我認爲它在這種情況下更清潔)

+0

非常感謝。至少這不是我的錯!我是RoR的新手,所以我會寫一個自定義驗證器。 – 2013-04-08 18:51:37

+0

與更新相得益彰。謝謝! – 2013-04-08 21:51:28