验证 :presence 与 validates_presence_of 使用 rails 3 [英] validates :presence vs validates_presence_of using rails 3
问题描述
我有几个简单的模型,它们像这样关联:
I have a couple of simple models that are associated like so:
模型
class Task < ActiveRecord::Base
belongs_to :user
validates :name, :presence => true, :message => 'Name cannot be blank, Task not saved'
end
class User < ActiveRecord::Base
has_many :tasks
end
VIEW 中有一个这样的调用:user.tasks
<-- 然后我遍历任务
VIEW has a call in it like so:
user.tasks
<-- then I loop through the tasks
问题:
在任务模型中 --
当我使用时:
validates :name, :presence => true , :message => 'Name cannot be blank, Task not saved'
我收到 500 错误:
I get a 500 error:
ActionView::Template::Error (uninitialized constant User::Task):
NameError in View file
当我使用时:
validates_presence_of :name
一切正常.
我认为上面的两种验证方法都相同……问题与关联以及验证如何与关联模型有关.我有一种预感,即事物的关联方式正在发生变化,但这只是一种预感.
I thought the both validates methods above where the same...is the issue have to do with associations and how validation tie into associated models. I have a hunch that something is going on with the way things are associated, but it is just a hunch.
任何帮助将不胜感激.非常感谢.
Any help will be appreciated. Thank very much.
推荐答案
当您使用较新的 validates :name
格式时,您可以将多个验证放在一行中,而不必将多行用于每种类型的验证.因此,当 Rails 遇到您的 :message
参数时,它会认为这是一种验证方法,而不是与 :presence
关联的消息.试试这个:
When you use the newer validates :name
format, you can put multiple validations in one line rather than having to have multiple lines for each type of validation. Because of this, when Rails hits your :message
parameter, it thinks it's a validation method rather than a message associated with :presence
. Try this instead:
validates :name, :presence => {:message => 'Name cannot be blank, Task not saved'}
此外,根据您显示错误的方式,此错误实际上可能显示为Name Name cannot be....";如果是这样,您需要将消息设置为不能为空,任务未保存".
Also, depending on how you display your errors, this error may actually show up as 'Name Name cannot be....'; if so, you'll want to set the message to just 'cannot be blank, Task not saved'.
这篇关于验证 :presence 与 validates_presence_of 使用 rails 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!