0

我遇到了奇怪的情况 - 当我尝试更新模型时,它可能包含 Paperclip 的附件(我使用 postgres 作为 db),并使用以下代码我看到错误:

>> u.profile.avatar = nil
=> nil
>> u.save!
ActiveRecord::RecordInvalid: Avatar file size file size must be between 0 and 1048576 bytes.
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/validations.rb:1090:in `save_without_dirty!'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/dirty.rb:87:in `save_without_transactions!'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transactions.rb:200:in `save!'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/database_statements.rb:136:in `transaction'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transactions.rb:182:in `transaction'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transactions.rb:200:in `save!'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transactions.rb:208:in `rollback_active_record_state!'
        from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transactions.rb:200:in `save!'
        from (irb):8
        from :0

这种情况很奇怪,因为它在 sqlite3 上工作。

我的模型包含:

  has_attached_file :avatar, 
    :path => ':rails_root/public/assets/images/avatars/:id/:style/:basename.:extension',
    :url => ApplicationSettings.assets_host_url + '/assets/images/avatars/:id/:style/:basename.:extension',
    :default_style => :thumb,
    :default_url => ':default_url',
    :whiny_thumbnails => true,
    :styles => {
        :tiny => ['32x32>', :png],
        :small => ['75x75>', :png],
        :regular => ['100x100>', :png],
      }

  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif']
  validates_attachment_size :avatar, :less_than => 1.megabytes

你能帮我吗?

4

1 回答 1

1

Alison R. 对解决方案发表了评论,但让我写一个完整的解决方案。

尝试这个:

validates_attachment_size :avatar, :less_than => 1.megabytes,
  :unless => Proc.new {|model| model.avatar }
于 2010-02-18T20:05:07.263 回答