sts
sts

Reputation: 380

Validation issue using multiple Proc objects

I have validation with Proc and problem with it

validates :subcategory, presence: true, 
if: Proc.new {|product| product.detail.blank?} && Proc.new { |product|  product.category.id != 16 }

My problem is when i have true in second proc my validation fires.

Why is it so? Should it not return false because false && true=>false?

Upvotes: 1

Views: 118

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230471

Others have commented on better ways to implement what you want. I'll just point out the misunderstanding you have.

it should return false because false && true => false

Nope. Actually, it's Proc && Proc => Proc (proc1 && proc2 => proc2). So your first proc is ignored due to how && operator works (this happens at class loading time) and is never called, not even once.

Upvotes: 4

dnsh
dnsh

Reputation: 3633

I will recommend using a method in :if.

validates :subcategory, presence: true, if: :my_cond?

def my_cond?
  detail.blank? && category.id != 16
end 

It makes your code cleaner. if you figure out really good name for method my_cond? then your code will be more readable.

Upvotes: 2

Andrey Deineko
Andrey Deineko

Reputation: 52357

I think you'd be better of using single proc object:

validates :subcategory,
  presence: true,
  if: Proc.new { |product| product.detail.blank? && product.category.id != 16 }

Upvotes: 5

Related Questions