在不同模型中验证回形针文件的通用方法

时间:2013-10-28 11:37:34

标签: ruby-on-rails custom-validators

我有2个模特用户,公司

用户模型:

has_attached_file :avatar,
             ...
                :whiny=>false
validates_with ImageSizeValidator
validates_with ImageTypeValidator
validates_with ImageConvertionValidator

公司型号:

has_attached_file :logo,
#the rest is similar

我已经对用户进行了验证并将其放入validation_helper

class ImageSizeValidator < ActiveModel::Validator
 def validate(record)
   if record.avatar_file_name.present?
     record.errors[:base] << (I18n.t :in_between, scope:  "activerecord.errors.models.user.attributes.avatar_file_size") unless record.avatar_file_size.to_i < 200000
   end
 end
end
class ImageTypeValidator < ActiveModel::Validator
 def validate(record)
  if record.avatar_file_name.present?
    record.errors[:base] << (I18n.t :file_type, scope: "activerecord.errors.models.user.attributes") unless ['image/jpeg', 'image/gif','image/png'].include?(record.avatar_content_type)
  end
 end
end

我的问题是名称会有所不同,因此用户的avatar_file_name和公司的徽标。

我是否必须为每种方法做一个特定的方法? 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

Paperclip内置了对验证的支持(https://github.com/thoughtbot/paperclip#validations)。如果他们的验证不适合您的问题,您可以查看他们是如何做到的:https://github.com/thoughtbot/paperclip/tree/master/lib/paperclip/validators

答案 1 :(得分:1)

你只需要添加选项。如果您查看documentation,可以在块中传递参数:

#model
validates_with ImageSizeValidator, paperclip_field_name: :avatar

#validator
 def validate(record)
   if record.send(options[:paperclip_field_name].to_s+"_file_name").present?
     record.errors[:base] << (I18n.t :in_between, scope:  "activerecord.errors.models.user.attributes.#{options[:paperclip_field_name]}_file_size") unless record.send(options[:paperclip_field_name].to_s+"_file_name").to_i < 200000
   end
 end

但更容易使用validate_each方法

#model
validates :avatar, image_size: true, image_type: true, image_conversion: true

#validator
def validate_each(record, attribute, value)
  if record.send(attribute.to_s+"_file_name").present?
    record.errors[:base] << (I18n.t :in_between, scope:  "activerecord.errors.models.user.attributes.#{attribute}_file_name)") unless record.send(attribute.to_s+"_file_name").to_i < 200000
  end
end