Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

How do you do something like this?

like image 351
Andrew Avatar asked Feb 20 '11 18:02

Andrew


2 Answers

: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

like image 50
Dogbert Avatar answered Oct 14 '22 01:10

Dogbert


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
like image 39
Michelle Tilley Avatar answered Oct 14 '22 02:10

Michelle Tilley