Paper clip image name changed after updating any attribute

This is my model

class Technology < ActiveRecord::Base attr_accessible :name #etc .... has_attached_file :logo, :path => ":rails_root/public/technologies/logos/:normalized_input_file_name" Paperclip.interpolates :normalized_input_file_name do |attachment, style| attachment.instance.normalized_input_file_name end def normalized_input_file_name name = "#{self.name}".downcase "#{self.tuid}_"+name.gsub(/[^a-zA-Z0-9]{2,}/,' ').strip.gsub(/\W/,'_').gsub(/\A_/,'').gsub(/_\z/,'')+"_150x"+".png" end end 

When I create any technology, I upload the logo and image stored in the public directory with a new name for it, since I want to use the "normalized_input_file_name" method. For example, the technology name is HTML5, and the file name becomes id_html5_150x.png But when I need to update the name, the image path also changed. for example, the HTML 5 file name becomes id_html_5_150x.png Here the actual image file name is not updated But the path is updated. Therefore, I can not find the image.

+4
source share
1 answer

Use before_save hook to load and save the image again if you find out that the name attribute changes.

This code is not fully tested, but should give you an idea:

 before_save do if self.name_changed? self.logo = logo.uploaded_file end end 
0
source

Source: https://habr.com/ru/post/1482933/


All Articles