即使输入数据,Rails 验证也会失败

发布于 2024-11-09 04:05:20 字数 734 浏览 0 评论 0原文

以下是我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千寻… 2024-11-16 04:05:20
:firstName=>"matt", :lastName=>"master", :gender => 1

检查该键是否与您的模型列相对应。似乎一切都应该好起来。

:firstName=>"matt", :lastName=>"master", :gender => 1

check that the key correspond to your model columns. Seems to be everything should be fine.

幽蝶幻影 2024-11-16 04:05:20

我怀疑此错误与您使用 .create! 方法从控制台创建和保存对象有关。您的 Person 类似乎需要一个外键,当您在控制台创建对象时,该值可能不会被实例化。要测试这一点,请尝试

test = Person.create(:firstName=>"matt", :lastName=>"master", :gender => 1)

在 .create 方法之后键入:,不带任何感叹号。这不应产生错误。现在输入:

test

很可能您已将所需的键值设置为“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:

test = Person.create(:firstName=>"matt", :lastName=>"master", :gender => 1)

with no bang after the .create method. This should not generate an error. Now type:

test

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文