我已将我的模型设置为使用多态图像模型。这工作正常,但我想知道是否可以更改每个模型的 :styles 设置。找到了一些使用 STI (Model < Image) 的示例,但这对我来说不是一个选项,因为我使用的是 has_many 关系。
艺术
has_many :images, :as => :imageable
图片
belongs_to :imageable, :polymorphic => true
has_attached_file :file, :styles => { :thumb => "150x150>", :normal => "492x600>"}
#Change this setting depending on model
更新
我尝试在 Proc 方法中启动调试器。仅填充与附件相关的字段:
run'irb(Image):006:0> a.instance => #<Image id: nil, created_at: nil, updated_at: nil, imageable_id: nil, imageable_type: nil, file_file_name: "IMG_9834.JPG", file_content_type: "image/jpeg", file_file_size: 151326, file_updated_at: "2010-10-30 08:40:23">
这是来自 ImageController#create 的对象
ImageController#create
@image => #<Image id: nil, created_at: nil, updated_at: nil, imageable_id: 83, imageable_type: "Art", file_file_name: "IMG_9834.JPG", file_content_type: "image/jpeg", file_file_size: 151326, file_updated_at: "2010-10-30 08:32:49">
我正在使用回形针 (2.3.5) 和 Rails 3.0.1。无论我做什么,a.instance 对象都是只填充了与附件相关的字段的图像。有什么想法吗?
更新2
在 Paperclip 论坛上阅读了大量内容后,我认为在保存之前不可能访问该实例。您只能看到 Paperclip 的东西,仅此而已。
我通过使用前置过滤器从图像 Controller 中预存图像来解决这个问题 - 没有附件
before_filter :presave_image, :only => :create
...
private
def presave_image
if @image.id.nil? # Save if new record / Arts controller sets @image
@image = Image.new(:imageable_type => params[:image][:imageable_type], :imageable_id => params[:image][:imageable_id])
@image.save(:validate => false)
@image.file = params[:file] # Set to params[:image][:file] if you edit an image.
end
end
最佳答案
我真的迟到了,但我想澄清一些关于访问此线程上发生的其他任何人的模型数据的事情。我只是在使用 Paperclip 根据模型数据应用水印时遇到了这个问题,经过大量调查后它开始工作了。
你说:
After reading a lot on the Paperclip forum I don't believe it's possible to access the instance before it has been saved. You can only see the Paperclip stuff and that's it.
事实上,您可以看到模型数据如果在您的附件被分配之前已经在对象中设置!
当您的模型中的附件被分配时,您的回形针处理器和诸如此类的东西被调用。如果您依赖批量分配(或者实际上不依赖),只要为附件分配了一个值,回形针就会执行它的操作。
这是我解决问题的方法:
在带有附件(照片)的模型中,我将附件以外的所有属性设置为 attr_accessible
,从而防止在批量分配期间分配附件。
class Photo < ActiveRecord::Base
attr_accessible :attribution, :latitude, :longitude, :activity_id, :seq_no, :approved, :caption
has_attached_file :picture, ...
...
end
在我的 Controller 的创建方法(例如)中,我从 params
中提取了 picture
,然后创建了对象。 (可能没有必要从 params
中删除图片,因为 attr_accessible
语句应该防止 picture
被分配,但它不会造成伤害)。 然后我分配 picture
属性,在照片对象的所有其他属性都已设置之后。
def create
picture = params[:photo].delete(:picture)
@photo = Photo.new(params[:photo])
@photo.picture = picture
@photo.save
...
end
在我的例子中,其中一种图片样式要求应用水印,这是 attribution
属性中保存的文本字符串。在我进行这些代码更改之前,从未应用属性字符串,并且在水印代码中,attachment.instance.attribution
始终为 nil
。此处总结的更改使整个模型在回形针处理器中可用。 关键是分配您的附件属性last。
希望这对某人有帮助。
关于ruby-on-rails - 回形针 :style depending on model (has_many polymorphic images),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4043640/