使用关联模型重命名图像 – Paperclip

在我的图像模型中:

has_attached_file :pic before_post_process :rename_pic before_save ->{ p 'before_save ----------------' } after_post_process ->{ p 'after_post_process --------------' } def rename_pic p 'en imagen' p self p 'en imagen' end 

在服务中有很多图像:

  # don't use accepts_nested_attributes_for before_save :create_images attr_accessor :images_attributes def create_images # images_attributes example value: { "0"=> {img_attrs}, "1" => {img_attrs1} } images_attributes.all? do |k, image_attrs| if image_attrs.delete(:_destroy) == "false" p 'asd' image = Image.new image_attrs.merge(service_id: id) p image.service p image.service_id image.save end end end 

这是我得到的输出:

 "asd" "en imagen" # "en imagen" G"after_post_process --------------" #<Service id: 427, event_id: nil, min_capacity: nil, max_capacity: nil, price: #, image_path: nil, name: "Super Franks", desc: "zxc", created_at: "2013-05-12 19:01:54", updated_at: "2013-07-30 19:32:48", address: "pasadena", longitude: 77.225, latitude: 28.6353, gmaps: true, city: "san francisco", state: "california", country_id: "472", tags: "Banquet", created_by: 22, avg_rating: #, views: 27, zip_code: "", address2: "", price_unit: "", category_id: 3, featured: true, publish: true, slug: "banquet-super-franks", discount: nil, currency_code: "USD", video_url: "http://www.youtube.com/watch?v=A3pIrBZQJvE", short_description: ""> 427 "before_save ----------------" 

问题

打电话时

 image = Image.new image_attrs.merge(service_id: id) 

Paperclips似乎开始处理,然后设置service_id。

所以当我尝试使用rename_pic服务时,服务是nil

关于如何处理这个问题的任何想法?

这解决了我的问题,我改变了:

 before_post_process :rename_pic 

至:

 before_create :rename_pic 

这是rename_pic,用于记录:

 def rename_pic extension = File.extname(pic_file_name).downcase self.pic.instance_write :file_name, "#{service.hyphenated_for_seo}#{extension}" end 

service has_many imagesimage belongs_to service

小心@juanpastas的修复,因为如果你将before_post_process更改为before_create ,它只会在你创建你的图像时运行,而不是在你更新它时运行 。 要使回调仍在更新时运行,请执行以下操作:

 class YourImage has_attached_file :pic # use both callbacks before_create :rename_pic before_post_process :rename_pic def rename_pic # assotiated_object is the association used to get pic_file_name return if self.assotiated_object.nil? extension = File.extname(pic_file_name).downcase self.pic.instance_write :file_name, "#{service.hyphenated_for_seo}#{extension}" end end