简体   繁体   English

Rails:验证foo的存在,除非bar =='baz'

[英]Rails: validate presence of foo unless bar == 'baz'

I'm working on a model that has two associations that need to be set when an object is created, EXCEPT in one case. 我正在研究一个模型,该模型在创建对象时需要设置两个关联,在一种情况下除外。

Basically, it needs to work like this. 基本上,它需要像这样工作。

class Example < ActiveRecord::Base
  has_one :foo
  has_one :bar

  validates_presence_of :foo
  validates_presence_of :bar, :unless => :foo == Foo.find_by_name('ThisFooDoesntLikeBars')
end

I'm not sure how to build the :unless condition here, as it needs to check whether :foo is a specific object or not. 我不确定如何构建:除非条件在这里,因为它需要检查:foo是否是特定对象。

How do you do something like this? 你怎么做这样的事情?

:unless accepts a Proc :unless接受Proc

  validates_presence_of :bar, :unless => Proc.new { |ex| ex.foo == Foo.find_by_name('ThisFooDoesntLikeBars') }

:unless - Specifies a method, proc or string to call to determine if the validation should not occur (eg :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). :unless - 指定要调用的方法,proc或字符串,以确定是否不应进行验证(例如:unless =>:skip_validation,或:unless => Proc.new {| user | user.signup_step <= 2})。 The method, proc or string should return or evaluate to a true or false value. 方法,proc或string应返回或计算为true或false值。

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

How about the following: 以下内容如何:

class Example < ActiveRecord::Base
  has_one :foo
  has_one :bar

  validates_presence_of :foo
  validates_presence_of :bar, :unless => Proc.new { |example| example.foo == Foo.find_by_name('ThisFooDoesntLikeBars') }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM