在Rails中仅运行回形针验证

时间:2012-05-16 11:22:42

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

我建模资料

class Profile < Abstract
    has_attached_file :avatar,                   
    ...
    validates_attachment_size :avatar, :less_than => 2.megabytes
    validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png', ...]
    # Many other validations
end

我有两种不同的形式:一种用于头像,另一种用于所有其他领域。用户必须能够保存头像而不填写第二种形式。是否可以仅验证回形针附件,跳过所有其他验证?在this回答后,我尝试这样做:

class Abstract < ActiveRecord::Base  
    def self.valid_attribute?(attr, value)
        mock = self.new(attr => value)
        unless mock.valid?
           return !mock.errors.has_key?(attr)
        end
        true
    end
end

并在控制器中

def update_avatar
    if params[:profile] && params[:profile][:avatar].present? && Profile.valid_attribute?(:avatar, params[:profile][:avatar])
        @profile.avatar = params[:profile][:avatar]
        @profile.save(:validate => false)
        ...
    else
        flash.now[:error] = t :image_save_failure_message
        render 'edit_avatar'
    end
end

但它不适用于回形针。 Profile.valid_attribute?(:avatar, params[:profile][:avatar])总是返回true。

1 个答案:

答案 0 :(得分:0)

不要试图做所有这些魔术,而是创建一个单独的Image或Avatar模型,它将成为你的图像模型,如:

class Attachment < ActiveRecord::Base

  belongs_to :owner, :polymorphic => true

  has_attached_file :file,
                :storage => :s3,
                :s3_credentials => "#{Rails.root}/config/s3.yml",
                :s3_headers => {'Expires' => 5.years.from_now.httpdate},
                :styles => { :thumbnail => "183x90#", :main => "606x300>", :slideshow => '302x230#', :interview => '150x150#' }

  def url( *args )
    self.file.url( *args )
  end

end

完成后,创建关系:

class Profile < Abstract
  has_one :attachment, :as => :owner, :dependent => :destroy
end

然后,在您的表单中,您首先保存附件,与您的模型无关,然后尝试保存配置文件设置附件。可能是这样的:

def create

  @attachment = if params[:attachment_id].blank?
    Attachment.create( params[:attachment )
  else
    Attachment.find(params[:attachment_id])
  end

  @profile = Profile.new(params[:profile])
  @profile.image = attachment unless attachment.new_record?
  if @profile.save
    # save logic here
  else
    # else logic here
  end 
end

然后,在您看来,如果个人资料无效,您可以将新保存的附件发送到表单,然后重复使用,而不必再次创建。