Paperclip :style depending on model (has_many polymorphic images)

后端 未结 10 921
醉梦人生
醉梦人生 2021-02-03 11:33

I have set up my models to use a polymorphic Image model. This is working fine, however I am wondering if it is possible to change the :styles setting for each model. Found some

10条回答
  •  别跟我提以往
    2021-02-03 12:17

    Looking at the Paperclip source for Attachment it looks like the styles hash can take an object that responds to call so you may be able to do something like:

    class Image < ActiveRecord::Base
      belongs_to :imageable, :polymorphic => true
      has_attached_file :file, :styles => lambda {|attachment| attachment.instance.imageable_type.constantize.image_styles }
    end
    

    Then in any model that has many images:

    class Art < ActiveRecord::Base
      has_many :images, :as => :imageable
    
      def self.image_styles
        { :thumb => "150x150>", :normal => "492x600>" }
      end
    end
    

    Edit: Looks like someone else beat me to it :P.

提交回复
热议问题