我正在使用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。
非常感謝。至少這不是我的錯!我是RoR的新手,所以我會寫一個自定義驗證器。 – 2013-04-08 18:51:37
與更新相得益彰。謝謝! – 2013-04-08 21:51:28