【问题标题】:Running only paperclip validations in Rails在 Rails 中只运行回形针验证
【发布时间】:2012-05-16 11:22:42
【问题描述】:

我有模特个人资料

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。

【问题讨论】:

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


    【解决方案1】:

    与其尝试做所有这些魔法,不如创建一个单独的图像或头像模型,作为您的图像模型,如下所示:

    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
    

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

    【讨论】:

    • 谢谢。我认为这是一个可能的解决方案。但我需要一个没有单独模型的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多