Ruby-on-rails ArgumentError:您需要提供至少一个验证:如果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8282167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:24:56  来源:igfitidea点击:

ArgumentError: You need to supply at least one validation with :if

ruby-on-railsvalidationruby-on-rails-3.1

提问by Ximik

I have a simple model

我有一个简单的模型

class Task < ActiveRecord::Base
  validates :deadline, :if => :deadline_in_future?

  def deadline_in_future?
    Date.today < self.deadline
  end
end

All seems ok, but when I in my rails console

一切看起来都很好,但是当我在我的 Rails 控制台中时

irb(main):001:0> Task.new
ArgumentError: You need to supply at least one validation

Where is the problem?

问题出在哪儿?

回答by zarne

You must change validatesto validate.

您必须更改validatesvalidate

回答by mu is too short

You forgot to tell validateshow you want to validate :deadline. I think you're misunderstanding what :ifdoes; the :if => :deadline_in_future?option means:

你忘了告诉validates你想如何验证:deadline。我认为你误解了什么:if;该:if => :deadline_in_future?选项意味着:

Validate :deadlineonly if the deadline_in_future?method returns a true value.

:deadline仅当该deadline_in_future?方法返回真值时才进行验证。

I suspect that you want to validate that the deadline is in the future:

我怀疑您想验证截止日期是在未来:

validate :deadline_in_future?

Further details are available in the Active Record Validations and Callbacks Guide.

更多细节可以在Active Record Validations and Callbacks Guide 中找到

回答by KL-7

It says you do not pass any validations to validatesmethod. Like validates :presence, for example. What are you trying to validate?

它说你没有通过任何验证validates方法。像validates :presence,例如。你想验证什么?