即使输入数据,Rails 验证也会失败
以下是我在 Rails Console 中执行的命令:
Person.create!(:firstName=>"matt", :lastName=>"master", :gender => 1)
我的结果是此错误消息:
ActiveRecord::RecordInvalid: Validation failed: Firstname can't be blank
我的模型验证代码如下所示:
class Person < ActiveRecord::Base
belongs_to :user, :class_name => 'User', :foreign_key => 'fk_ssmUserId'
validates_presence_of :firstName, :lastName
当我注释掉 validates_presence_of
时,一切正常,并且我的数据已正确输入到数据库,所以我知道这些值实际上被传递到新对象中。我什至检查了 Rails::ActiveRecord::Validations 代码中创建的新对象,以确保它在保存之前已正确实例化。是的。另外,我还有其他带有 validates_presence_of 的模型,每次都能 100% 正常工作。这只是这一种型号。我正在使用 Rails 3.1.0.rc1。
有什么想法吗?
谢谢!
Here is the command that I'm executing in Rails Console:
Person.create!(:firstName=>"matt", :lastName=>"master", :gender => 1)
My result is this error message:
ActiveRecord::RecordInvalid: Validation failed: Firstname can't be blank
My model validation code looks as such:
class Person < ActiveRecord::Base
belongs_to :user, :class_name => 'User', :foreign_key => 'fk_ssmUserId'
validates_presence_of :firstName, :lastName
When I comment out validates_presence_of
everything works and my data is entered properly into the database, so I know that the values are actually being passed into the new object. I even inspected the new object created inside the Rails::ActiveRecord::Validations code to make sure it was being instantiated correctly before being saved. It was. Also, I have other models with validates_presence_of that work 100% fine every time. It's just this one model. I am using Rails 3.1.0.rc1.
Any ideas?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查该键是否与您的模型列相对应。似乎一切都应该好起来。
check that the key correspond to your model columns. Seems to be everything should be fine.
我怀疑此错误与您使用 .create! 方法从控制台创建和保存对象有关。您的 Person 类似乎需要一个外键,当您在控制台创建对象时,该值可能不会被实例化。要测试这一点,请尝试
在 .create 方法之后键入:,不带任何感叹号。这不应产生错误。现在输入:
很可能您已将所需的键值设置为“nil”,并且在您填写适当的值之前无法从控制台保存该对象。
I have a suspicion that this error relates to the fact that you're creating and saving the object using the .create! method from the console. Your Person class appears to require a foreign key, a value which is probably not being instantiated when you create an object at the console. To test this, try typing:
with no bang after the .create method. This should not generate an error. Now type:
It's very likely that you have required key values set as "nil" and that the object can't be saved from console until you fill in the appropriate values.