2

代码

在我的图像模型中:

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"
#<Image id: nil, service_id: nil, pic_file_name: "Screen_Shot_2013-04-07_at_5.18.03_PM.png", pic_content_type: "image/png", pic_file_size: 16041, pic_updated_at: "2013-07-30 22:58:46", created_at: nil, updated_at: nil, user_id: nil>
"en imagen"
G"after_post_process --------------"
#<Service id: 427, event_id: nil, min_capacity: nil, max_capacity: nil, price: #<BigDecimal:7fb6e9d73d48,'0.0',9(18)>, 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: #<BigDecimal:7fb6efdbcf10,'0.0',9(18)>, 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。

所以当我尝试使用service内部rename_pic服务时nil

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

4

2 回答 2

2

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

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 images, 和image belongs_to service.

于 2013-07-31T14:19:19.647 回答
0

小心@juanpastas 的修复,因为如果您更改before_post_processbefore_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
于 2015-06-04T08:56:47.217 回答