简体   繁体   English

通过回形针保存之前重命名图像-rails 2.3.5

[英]rename image before saving via paperclip - rails 2.3.5

I am using paperclip to allow user to upload images in my rails application. 我正在使用回形针允许用户在我的Rails应用程序中上传图像。

I want to rename the images uploaded by appending the current time to their file names before saving them in the database. 我想通过将当前时间附加到文件名来重命名上载的图像,然后再将它们保存在数据库中。

Here is my model. 这是我的模特。 The column 'data_file_name' is used to store the image name in the 'images' table. “ 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

When I try to upload an image, I get the error message below: 尝试上传图片时,出现以下错误消息:

 NoMethodError in BooksController#update

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

Any help? 有什么帮助吗?

Note that I am using rails 2.3.5 请注意,我正在使用Rails 2.3.5

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM