Rails 4 - 使用自定义回形针附件处理器解析参数的顺序

Posted

技术标签:

【中文标题】Rails 4 - 使用自定义回形针附件处理器解析参数的顺序【英文标题】:Rails 4 - order of param parsing with a custom paperclip attachment processor 【发布时间】:2015-01-23 11:21:47 【问题描述】:

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

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_wx" \
          "#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 在附件图像之前处理裁剪边界字段? 或者是否有其他解决方案基本上可以完成此任务?

【问题讨论】:

【参考方案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 实现发生变化,最终会很危险。 我遇到了完全相同的问题.. 感谢您的解决方案!

以上是关于Rails 4 - 使用自定义回形针附件处理器解析参数的顺序的主要内容,如果未能解决你的问题,请参考以下文章

如何将 pdf_file 传递给 rails 中的解析器方法?

Rails 4:如何使用 AJAX 上传文件

请建议适当的附件插件/宝石用于 Rails 2.0.2 和 Ruby 1.8.7

Rails 4 Paperclip with Devise,文件保存错误

在rails中处理后如何更新回形针视频位置

将 Rails 部分渲染到图像