Rails 3 + JQuery-File-Upload + Nested Model

前端 未结 3 665
面向向阳花
面向向阳花 2020-12-07 18:12

I\'ve been searching for some examples, but have come up short:

I\'m trying to implement JQuery-File-Upload on a project I\'m working on, but am getting lost as to h

3条回答
  •  甜味超标
    2020-12-07 18:40

    I have a similar setup running with Carrierwave. Here's what I have. I'm using Images as a nested resource for Projects.

    Project.rb:

    has_many :images, :dependent => :destroy
    accepts_nested_attributes_for :images, :allow_destroy => true
    

    Image.rb:

     include Rails.application.routes.url_helpers
      mount_uploader :image, ImageUploader
    
      belongs_to :project
    
      #one convenient method to pass jq_upload the necessary information
      def to_jq_upload
      {
        "name" => read_attribute(:image),
        "size" => image.size,
        "url" => image.url,
        "thumbnail_url" => image.thumb.url,
        "delete_url" => image_path(:id => id),
        "delete_type" => "DELETE" 
       }
      end
    

    Images_controller.rb:

     def create
        @image = Image.new(params[:image])
        @image.project_id = params[:project_id]
        @project = Project.find(params[:project_id])
        @image.position = @project.images.count + 1
        if @image.save
          render :json => [ @image.to_jq_upload ].to_json
        else
          render :json => [ @image.to_jq_upload.merge({ :error => "custom_failure" }) ].to_json
        end
      end
    

    Be aware, this was a *!@^%! to get working.

    UPDATE: projects/_form.html.erb

    <%= form_for Image.new, :html => {:multipart => true} do |f| %>
    <% end %>
    Drop Image Files Here

提交回复
热议问题