Ruby on Rails - Paperclip and dynamic parameters

前端 未结 3 1840
长情又很酷
长情又很酷 2021-02-04 15:24

I\'m writing some image upload code for Ruby on Rails with Paperclip, and I\'ve got a working solution but it\'s very hacky so I\'d really appreciate advice on how to better imp

3条回答
  •  遇见更好的自我
    2021-02-04 16:20

    I've just solved a similar problem that I had. In my "styles" lambda I am returning a different style depending on the value of a "category" attribute. The problem though is that Image.new(attrs), and image.update_attributes(attrs) doesn't set the attributes in a predictable order, and thus I can't be guaranteed that image.category will have a value before my styles lambda is called. My solution was to override attributes=() in my Image model as follows:

    class Image
      ...
      has_attached_file :image, :styles => my_lambda, ...
      ...
      def attributes=(new_attributes, guard_protected_attributes = true)
        return unless new_attributes.is_a?(Hash)
        if new_attributes.key?("image")
          only_attached_file    = {
            "image" => new_attributes["image"]
          }
          without_attached_file = new_attributes
          without_attached_file.delete("image") 
          # set the non-paperclip attributes first
          super(without_attached_file, guard_protected_attributes)
          # set the paperclip attribute(s) after
          super(only_attached_file, guard_protected_attributes)
        else
          super(new_attributes, guard_protected_attributes)
        end
      end
      ...
    end
    

    This ensures that the paperclip attribute is set after the other attributes and can thus use them in a :style lambda.

    It clearly won't help in situations where the paperclip attribute is "manually" set. However in those circumstances you can help yourself by specifying a sensible order. In my case I could write:

    image = Image.new
    image.category = "some category"
    image.image = File.open("/somefile") # styles lambda can use the "category" attribute
    image.save!
    

    (Paperclip 2.7.4, rails 3, ruby 1.8.7)

提交回复
热议问题