gpt4 book ai didi

ruby-on-rails-3 - 验证 :presence vs validates_presence_of using rails 3

转载 作者:行者123 更新时间:2023-12-03 11:08:14 25 4
gpt4 key购买 nike

我有几个简单的模型,它们像这样关联:

楷模

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 <-- 然后我循环执行任务

问题:

在任务模型中——

当我使用:
validates :name, :presence => true ,  :message => 'Name cannot be blank, Task not saved'

我收到 500 错误:
ActionView::Template::Error (uninitialized constant User::Task):
NameError in View file

当我使用:
validates_presence_of :name

一切正常。

我认为上面的两种验证方法都相同……问题与关联以及验证如何与关联模型有关。我有一种预感,事物的关联方式正在发生某些事情,但这只是一种预感。

任何帮助将不胜感激。非常感谢。

最佳答案

当您使用较新的 validates :name格式,您可以将多个验证放在一行中,而不必为每种类型的验证设置多行。因此,当 Rails 遇到您的 :message 时参数,它认为它是一种验证方法,而不是与 :presence 相关联的消息.试试这个:

validates :name, :presence => {:message => 'Name cannot be blank, Task not saved'}

此外,根据您显示错误的方式,此错误实际上可能显示为“Name Name cannot be....”;如果是这样,您需要将消息设置为“不能为空,任务未保存”。

关于ruby-on-rails-3 - 验证 :presence vs validates_presence_of using rails 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com