我正在研究一个模型,该模型在创建对象时需要设置两个关联,在一种情况下除外.
基本上,它需要像这样工作.
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
我不确定如何构建:除非条件在这里,因为它需要检查:foo是否是特定对象.
你怎么做这样的事情?
解决方法
:除非接受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 (e.g. :unless => :skip_validation,or :unless => Proc.new { |user| user.signup_step <= 2 }). The method,proc or string should return or evaluate to a true or false value.
http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html