微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Paperclip:样式取决于模型(has_many多态图像)

我已经设置了我的模型来使用多态图像模型.这是正常工作,但我想知道是否可以更改每个模型的样式设置.发现一些使用STI(模型< 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

UPDATE

我尝试在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#创建的对象

ImageController#create
@image => #<Image id: nil,imageable_id: 83,imageable_type: "Art",file_updated_at: "2010-10-30 08:32:49">

我正在使用回形针(2.3.5)和Rails 3.0.1.无论我做什么,a.instance对象是只有与附件填充相关的字段的图像.有任何想法吗?

UPDATE2

在Paperclip论坛上阅读了很多,我不相信在保存实例之前可以访问该实例.你只能看到Paperclip的东西,就是这样.

我已经解决了这个问题,从图像控制器的前一个过滤器 – 没有附件的图像

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

在我的控制器的创建方法(例如)中,我从参数中拉出图片,然后创建对象. (可能没有必要从params中删除图片,因为attr_accessible语句应该防止图片被弄脏,但不会受到伤害).然后在照片对象的所有其他属性设置完毕后,我分配图片属性.

def create
  picture = params[:photo].delete(:picture)
  @photo = Photo.new(params[:photo])
  @photo.picture = picture

  @photo.save
  ...
end

在我的情况下,应用水印的图片调用的样式之一,即属性属性中保存的文本字符串.在我做这些代码更改之前,归因字符串从未被应用,而在水印代码中,attachment.instance.attribution总是为零.这里总结的更改使整个模型可用在回形针处理器中.关键是最后分配你的附件属性.

希望这有助于某人.

原文地址:https://www.jb51.cc/ruby/266266.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐