随机化Paperclip图像名称Rails

时间:2013-09-18 01:16:09

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

您好我正在使用本教程来实现图像的随机名称 http://trevorturk.com/2009/03/22/randomize-filename-in-paperclip/

问题是我得到了这个错误。

   NameError in RegistrationsController#create

undefined local variable or method `image_file_name' for #<Player:0xbd66ae0>
Rails.root: /srv/www/myfootballproject.com/mfp

Application Trace | Framework Trace | Full Trace
app/models/player.rb:143:in `randomize_file_name'
app/models/user.rb:29:in `is_a_player?'

以下是造成问题的模型部分

这是模特中player.rb上“class Player”内的部分视图。

has_attached_file :avatar, :styles => { :profile => "300x300", :thumb => "100x100#"},
    :url  => "/assets/people/:id/:style/:basename.:extension",
    :path => ":rails_root/public/assets/people/:id/:style/:basename.:extension"

    before_create :randomize_file_name

    validates_attachment_size         :avatar, :less_than    => 2.megabytes # Solo aceptar imágenes menores a 2 Mb.
    validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif']

  private

    def randomize_file_name
      extension = File.extname(image_file_name).downcase
      self.image.instance_write(:file_name, "#{ActiveSupport::SecureRandom.hex(16)}#{extension}")
    end


    def defeated?
      t = Time.now - created_at

      mm, ss = t.divmod(60)
      hh, mm = mm.divmod(60)
      dd, hh = hh.divmod(24)

      dd > 180 ? true : false
    end

1 个答案:

答案 0 :(得分:3)

对于任何寻找此事的人,不要破坏你的头XD这已经在Paperclip中完成了

has_attached_file :avatar, :styles => { :profile => "300x300", :thumb => "100x100#"},
    :url  => "/assets/people/:id/:style/:basename.:extension",
    :path => ":rails_root/public/assets/people/:id/:style/:hash.:extension",
    :hash_secret => "longSecretString"

此处所有信息

https://github.com/thoughtbot/paperclip#uri-obfuscation