在url回形针中插入多态关系类型

时间:2014-04-02 14:10:42

标签: ruby-on-rails ruby-on-rails-3 activerecord paperclip

我有一个多态的照片模型

class Photo < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
 has_attached_file :image,
                :styles => {:thumb => '120x120>', :medium => '640x480>' },
                :default_style => :thumb,
                :url => "/uploads/photos/#{model.imageable_type.to_s.pluralize.underscore}/:id/:basename.:extension"

class Question < ActiveRecord::Base
has_one :photo, as: :imageable, dependent: :destroy


class Answer < ActiveRecord::Base
has_one :photo, as: :imageable, dependent: :destroy

这会生成url as uploads / photos / Photo / some_id / file_name.ext 但是我想要

public/uploads/photos/questions/1/image.jpg

public/uploads/photos/answers/1/image.jpg.

1 个答案:

答案 0 :(得分:1)

自己解决了。

   :url => "/uploads/photos/:imageable_name/:id/:basename.:extension"


Paperclip.interpolates :imageable_name  do |attachment, style|
  attachment.instance.imageable_type.pluralize.downcase
end