rails字段验证

时间:2016-06-12 17:40:04

标签: ruby-on-rails database validation

我的模型Product包含字段:

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

如何使此验证适用于Product模型create操作?

- 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 个答案:

答案 0 :(得分: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