Rails,如何为 Active Admin 删除 validates_attachment_content_type?

Rails, How to remove validates_attachment_content_type for Active Admin?

我正在使用回形针让用户拥有自己的头像。我注意到,当我转到活动管理员编辑或创建新用户时,当该用户没有头像时,我会在头像内容类型字段中得到一个 "avatar content type is invalid error"。

我可以通过在字段中输入 image/jpeg 来克服这个错误,但显然这对于​​其他管理员用户来说并不理想,因为他们每次想要创建或编辑用户时都必须输入。

User.rb

....   has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"
      validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/....

有没有办法通过隐藏字段或其他方法来保持验证但为活动管理员关闭验证?谢谢。

您必须在管理员中自定义 createupdate 方法。例如:

controller do
  def update
    @user = User.find(params[:id])
    @user.assign_attributes(params[:user], as: :admin)
    @user.save(validate: false)
    redirect_to edit_admin_user_path(@user), :notice => "User Account Updated"
  end
end

我想使用虚拟属性来跳过图像验证。

在用户模型中:

# models/user.rb
attr_accessor :skip_image_validation

validates_attachment_content_type :avatar ... , unless: lambda { skip_image_validation.present? }

并在活动管理员的 before_save 回调中,将 :skip_image_validation 分配给 true like

# admin/user.rb
ActiveAdmin.register User do

  before_save do |user|
    user.skip_image_validation = true
  end
...