0
votes

I am using paperclip to allow user to upload images in my rails application.

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.

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

1

1 Answers

0
votes

You can adjust the path to change the file name e.g.

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