[英]RoR - Validates_existence_of with nil foreign key not working
I am using the validates_existence_of gem. 我正在使用validates_existence_of gem。 It works well except when I want to allow my foreign key to be nil. 除非我要允许外键为零,否则它运行良好。
Here are my models for User and Project. 这是我的用户和项目模型。 A project belongs_to a user and a contributor (a contributor is also a user), but the contributor can be nil. 一个项目属于一个用户和一个贡献者(一个贡献者也是一个用户),但是贡献者可以为nil。
Here is my user model: 这是我的用户模型:
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name
has_many :projects, :dependent => :destroy
has_many :user_trimester_statuses, :dependent => :destroy
end
And here is my project model: 这是我的项目模型:
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
When I try to add a new project, I have an error if the user_id or trimester_id field is blank or invalid. 当我尝试添加新项目时,如果user_id或trimester_id字段为空白或无效,则会出现错误。 But for the contributor_id field, there is no error thrown if the field is invalid. 但是对于contributor_id字段,如果该字段无效,则不会引发任何错误。 It goes through either way (valid, invalid, or nil). 它通过两种方式(有效,无效或无)进行。
What am I doing wrong? 我究竟做错了什么? I am using ruby 2.0.0p0 and rails 3.2.13. 我正在使用ruby 2.0.0p0和rails 3.2.13。
It looks like there is an open bug about this in the project. 看起来在项目中有一个关于此的打开错误。
https://github.com/perfectline/validates_existence/issues/15 https://github.com/perfectline/validates_existence/issues/15
You may have to write a simple custom validator for this case until this gets fixed. 在这种情况下,您可能必须为这种情况编写一个简单的自定义验证器。 (or dig in and see if you can fix the issue yourself) (或深入了解是否可以自己解决问题)
UPDATE: I just cloned the project and wrote a test to see what the issue was. 更新:我只是克隆了该项目,并编写了一个测试以查看问题所在。 It seems that when you add the allow_nil, the existence validator doesn't get called at all. 似乎在添加allow_nil时,根本不会调用存在验证器。 I'm not sure why that is, but in the meantime, you can work around the bug in an easy way, by using a proc. 我不确定为什么会这样,但是与此同时,您可以使用proc轻松解决该错误。 instead of 代替
validates :contributor, :existence => { :allow_nil => true, :both => false }
this would get the job done 这将完成工作
validates_existence_of :contributor, :unless => Proc.new { |obj| obj.contributor_id.blank? }
I was able to prove that in my test case. 我可以在测试案例中证明这一点。 (I went with the 'validates_existence_of' method, instead of 'validates', because I thought it was cleaner in this case) (我使用了“ validates_existence_of”方法,而不是“ validates”,因为我认为在这种情况下它更干净)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.