有条件的纸夹存在验证

4

如果另一个字段存在,我该如何验证没有纸夹附件?我尝试过:

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? - lwiseman
3个回答

2

我这里也遇到了类似的问题,我的解决方法是在函数中进行比较。

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

1
尝试这个:-
validates_attachment :img, presence: true, if: :some_other_field?
def some_other_field?
  some_other_field.present?
end

0

你试过使用exists?而不是present?吗,它可能会有效。

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

刚尝试了这种方式,以及Techvineet和Aman的方式。没有任何进展。 - lwiseman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接