Ruby on Rails - Paperclip and dynamic parameters

前端 未结 3 1804
长情又很酷
长情又很酷 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 15:58

    While I really like Cade's solution, just a suggestion. It seems like the 'styles' belong to a project...so why aren't you calculating the generators there?

    For example:

    class Asset < ActiveRecord::Base
      attr_accessible :filename,
      :image # etc.
       attr_accessor :generators
    
       has_attached_file :image,
         :styles => lambda { |a| a.instance.project.styles }
    end
    
    
     class Project < ActiveRecord::Base
       ....
    
       def styles
         @generators ||= self.generators.inject {} do |hash, g|
           hash[g.sym] = "#{g.width}x#{g.height}"
         end
       end
    end
    

    EDIT: Try changing your controller to (assuming the project has many assets):

    def create
      @project = Project.find(params[:project_id])
      @asset = @project.assets.new
      @asset.generators = @project.generators
      @asset.update_attributes(params[:asset])
      @asset.uploaded_by = current_user
    end
    

提交回复
热议问题