Paperclip :style depending on model (has_many polymorphic images)

后端 未结 10 1207
醉梦人生
醉梦人生 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:34

    I've also met with the same problem and after searching for an elegant solution I didn't found anything "really" useful. So, here's my simple solution which seems alright for now; (tho I'm not sure if it has any downsides for the moment)

    In model;

    class Asset < ActiveRecord::Base
      belongs_to :assetable, polymorphic: true
    
      has_attached_file :attachment,  path: ":rails_root/#{path}/assets/images/:style/:filename",
                                      url: '/assets/images/:style/:filename',
                                      styles: -> (a) { a.instance.send(:styles) }
    private
      def styles
        raise 'Undefined assetable.' unless assetable
    
        if assetable.class == Photo
          { small: 'x40', medium: '120x', large: '300x' }
        elsif assetable.class == Avatar
          { small: 'x40', medium: '120x', large: '300x' }
        else
          raise "Styles for #{assetable.class} is not defined."
        end
      end
    end
    

    In controller;

    @photo = Photo.new
    @photo.build_image(assetable: @photo, attachment: params[:photo][:image_attributes][:attachment])
    @photo.save
    

提交回复
热议问题