开发者

Rails: validate presence of foo unless bar == 'baz'

开发者 https://www.devze.com 2023-02-12 19:26 出处:网络
I\'m working on a model that has two associations that need to be set when an object is created, EXCEPT in one case.

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.

How do you do something like this?


:unless accepts a 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号