1

我有模特简介

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

我有两种不同的形式:一种用于头像,另一种用于所有其他领域。用户必须能够在不填写第二个表单的情况下保存头像。是否可以仅验证回形针附件,跳过所有其他验证?按照这个答案,我试图这样做:

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])总是返回真。

4

1 回答 1

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

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

于 2012-05-16T11:57:51.373 回答