1

I have a Model Product with fields:

name price product_type_id:integer size:string page_quantity:integer. 

How can make this validation work for Product model create action?

- if product_type.id == "1"
   validates :size, presence: true
   validates :page_quantity, presence:false
- else
   validates :size, presence: false
   validates :page_quantity, presence:true
end

1 Answer 1

2
   validates :size, presence: true, if: Proc.new { |p| p.product_type_id == "1" } 
   validates :page_quantity, presence:false, if: Proc.new { |p| p.product_type_id == "1" }
   validates :size, presence: false, unless: Proc.new { |p| p.product_type_id == "1" }
   validates :page_quantity, presence:true, unless: Proc.new { |p| p.product_type_id == "1" }
end
Sign up to request clarification or add additional context in comments.

2 Comments

I want the validation to be not to Product.id but if product_type_id == 1 in Product.create action
@makerbreaker adjusted, but I think that the main idea should be pretty clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.