为Paperclip Imagemagikresize的模型提供变量字符串

我正在使用paperclip上传一些resize的图像。 其中一个我想要被裁剪为五种方式中的一种……无论如何,我通过手工改变它们来确定要裁剪的弦应该是什么样的,但是现在我需要制作那种动态以便回形针可以裁剪的根据用户的意愿……

问题是我得到了

undefined local variable or method `params' for # 

我觉得很确定这是因为我试图按照我的意愿弯曲导轨。 无论如何,我认为我很清楚我正在尝试做什么……只需将crop_geometry_thumb变量提供给convert_options ……我应该在哪里实际使用我的模型才能找到它的逻辑?

 class Asset  { :large => ['700x700', :jpg], :medium => ['300x300>', :jpg], :thumb => ["200x200>", :jpg]}, :convert_options => {:thumb => crop_geometry_thumb}, ### supply a string from above... FAIL :( :path => ":id/:style/:filename", :storage => :s3, :s3_credentials => "#{RAILS_ROOT}/config/s3.yml", :s3_permissions => :private, :url => ':s3_domain_url' end 

因此,当前的问题是您的模型无法访问请求参数(即params[:crop_geometry] ),只能访问您的控制器+视图。

在某些情况下(虽然它从来都不是一个好主意),你可以通过将params传递给模型作为方法的参数来绕过这个MVC规则:

 class FoosController < ApplicationController def action Foo.some_method(params) end end class Foo < ActiveRecord::Base some_method(params) puts params[:crop_geometry] end end 

相反,我建议将该参数信息传递给模型中定义的实例变量,并将条件逻辑放入自定义的setter方法中,如下所示:

 class Asset < ActiveRecord::Base attr_reader :crop_geometry def crop_geometry=(crop_type) if crop_type == "bottom" crop_string = "-crop 200x100+0+100 -scale 100x100" elsif crop_type == "top" crop_geometry_thumb = "-crop 200x100+0+0 -scale 100x100" elsif crop_type == "left" crop_geometry_thumb = "-crop 100x200+0+100 -scale 100x100" elsif crop_type == "right" crop_geometry_thumb = "-crop 100x200+100+0 -scale 100x100" else crop_geometry_thumb = "-scale 100x100" end @crop_geometry = crop_geometry_thumb end end 

请注意,您必须更改表单,以便为params [:asset] [:crop_geometry]分配“top”,“bottom”或其他内容。

现在,要动态设置crop_geometry,您需要在has_attached_file配置中使用lambda - 这样每次访问配置时都会对其进行评估,而不仅仅是在最初加载模型时。 干得好:

 has_attached_file :asset, :styles => lambda {|attachment| :large => ['700x700', :jpg], :medium => ['300x300>', :jpg], :thumb => ["200x200>", :jpg]}, :convert_options => {:thumb => attachment.instance.crop_geometry}, :path => ":id/:style/:filename", ... } 

从https://github.com/thoughtbot/paperclip获得最后一部分(查找“动态配置”)。