【问题标题】:rename image before saving via paperclip - rails 2.3.5在通过回形针保存之前重命名图像 - rails 2.3.5
【发布时间】:2013-05-09 15:01:04
【问题描述】:

我正在使用回形针来允许用户在我的 rails 应用程序中上传图片。

我想通过将当前时间附加到它们的文件名来重命名上传的图像,然后再将它们保存到数据库中。

这是我的模型。 'data_file_name' 列用于将图像名称存储在 'images' 表中。

class Image < ActiveRecord::Base
  set_table_name "IMAGES"
  set_primary_key "id"


  before_create : :rename_image_file



  def rename_image_file
    extension = File.extname(data_file_name).downcase
    self.data_file_name.instance_write(:data_file_name, "#{Time.now.to_i.to_s}#{extension}")
  end



  belongs_to :book,:foreign_key => :book_id



  has_attached_file :data, :path => ":rails_root/public/book_images/:book_id/:style/:basename.:extension",
    :url => "http://www.test.org/book_test_editors/book_images/:book_id/:style/:basename.:extension",


  :styles => {
    :thumbnails => ["150x172#",:jpg],
    :large => ["100%", :jpg]
   }



end

当我尝试上传图片时,我收到以下错误消息:

 NoMethodError in BooksController#update

undefined method `instance_write' for "DSC02017.JPG":String

有什么帮助吗?

请注意,我使用的是 rails 2.3.5

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    您可以调整路径以更改文件名,例如

      has_attached_file :data, :path => ":rails_root/public/book_images/:book_id/:style/:basename.#{Time.now.to_i}.:extension",
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 2016-03-31
      相关资源
      最近更新 更多