【问题标题】:Conditional paperclip presence verification有条件的回形针存在验证
【发布时间】:2013-08-28 23:27:14
【问题描述】:

如果确实存在另一个字段,我如何验证回形针附件是否存在?我试过了:

validates_attachment :img, presence: false, if: :some_other_field?
def some_other_field?
  some_other_field
end

【问题讨论】:

  • 这是我确定的,但我仍在寻找更优雅的方式:validates :img_file_name, absence: true, if: :some_other_field?

标签: ruby-on-rails validation activerecord paperclip paperclip-validation


【解决方案1】:

这里有类似的问题,我的解决方法是在def中进行比较

validate :check_image_with_title 

def check_image_with_title
   if !ctitle.blank? and cimage.blank?
      #If ctitle IS NOT empty and cimage IS empty, add a custom error message
      errors.add :key, "You need an image to go with your title"
      return false
    else
      return true
   end 
end

【讨论】:

    【解决方案2】:

    试试这个:-

    validates_attachment :img, presence: true, if: :some_other_field?
    def some_other_field?
      some_other_field.present?
    end
    

    【讨论】:

      【解决方案3】:

      您是否尝试过使用exists? 而不是present?,可能有效

      validates_attachment :img, presence: false, if: :some_other_field?
      def some_other_field?
        some_other_field.exists?
      end
      

      【讨论】:

      • 刚刚尝试过这种方式以及techvineet的方式和Aman的方式。没有骰子。
      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多