仅在没有图像附件时才验证长度?

时间:2018-03-22 19:14:35

标签: ruby-on-rails

我试图只在没有图片但没有线索的情况下才会出现validates_length ...

 class Post < ApplicationRecord

     validates_attachment_content_type :pictures, content_type: /\Aimage\/.*\z/
     validates_length_of :description, :minimum => 3, :maximum => 200
 end

2 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是创建自定义验证方法,在内部可以检查两个条件

 validate :attachment_or_length

 def attachment_or_length
   content_type = self.try(:pictures).content-type.your_match_method
   desc_size = self.try(:description).size.between?(3,200)

   return if content_type or desc_size // validation passes

   errors.add(:pictures, "Content type doesn't match") unless content_type // fail
   errors.add(:description, "Description size has to be between 3 and 200") unless desc_size // fail
 end

答案 1 :(得分:1)

我使用Proc感到不满意,但可以使用:if选项完成此操作,如下所示:

class Post < ApplicationRecord
  validates_attachment_content_type :pictures, content_type: /\Aimage\/.*\z/, if: Proc.new { |a| a.description.nil? }
  validates_length_of :description, minimum: 3, maximum: 200, if: Proc.new { |a| a.pictures.nil? }
end