【问题标题】:Rails 4 - order of param parsing with a custom paperclip attachment processorRails 4 - 使用自定义回形针附件处理器解析参数的顺序
【发布时间】:2026-01-18 04:00:01
【问题描述】:

我有一个带有回形针图像附件的内容表以及一些用户选择的裁剪设置:

create_table "content", force: true do |t|
    t.string   "title"
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
    t.integer  "crop_x"
    t.integer  "crop_y"
    t.integer  "crop_w"
    t.integer  "crop_h"
end

为了在服务器端处理用户指定的图像裁剪,我有一个自定义的回形针处理器,我从 here 采购:

module Paperclip
  class CustomCropper < Thumbnail
    def initialize(file, options = {}, attachment = nil)
      super
      @current_geometry.width = target.crop_w
      @current_geometry.height = target.crop_h
    end
    def target
      @attachment.instance
    end
    def transformation_command
      crop_command = [
          '-crop',
          "#{target.crop_w}x" \
          "#{target.crop_h}+" \
          "#{target.crop_x}+" \
          "#{target.crop_y}",
          '+repage'
      ]
      crop_command + super
    end
  end
end

我的问题是crop_x,y,w,h 参数是在图像附件之后解析的,因此自定义回形针处理器在所有字段中都看到nil 并且不能正确裁剪图像。

# rails processes the image_xxx params before the crop_xxx params
@content = Content.new(content_params)

有没有一种简洁的方法告诉 Rails 在附件图像之前处理裁剪边界字段? 或者是否有其他解决方案基本上可以完成此任务?

【问题讨论】:

    标签: ruby-on-rails image paperclip


    【解决方案1】:

    对于我的一生,我想不出一个“干净”的方法。我最终做的是在使用附件调用更新/保存之前保存 crop_ 值。

    例如:

    def update
    
      if article_params[:image_crop_y].present?
        @article.image_crop_y = article_params[:image_crop_y]
        @article.image_crop_x = article_params[:image_crop_x]
        @article.image_crop_w = article_params[:image_crop_w]
        @article.image_crop_h = article_params[:image_crop_h]
        @article.save
      end
    
      if @article.update(article_params)
        ...
      end
    
    end
    

    就像我说的,不是“最干净”的方式,但它对我很有效。

    【讨论】:

    • 酷,谢谢蒂姆!我想我做了一些更骇人听闻的事情,那就是将作物字段放在数据库模式中的图像附件字段之前。 (Rails 按模式顺序处理参数)。所以代码看起来很干净,但如果 R​​ails 实现发生变化,最终会很危险。
    • 我遇到了完全相同的问题.. 感谢您的解决方案!
    最近更新 更多