Alex Rivera | Logout

Rails 3 + JQuery-File-Upload + Nested Model

Asked 2012-02-20T07:32:38.030
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 how to get it to work with nested attributes.

Quick overview:

2 Models:

Comment [has_many :attachments]
Attachment [belongs_to :comment]

Comment accepts_nested_attributes_for :attachments. Also - I'm using Dragonfly.

I've reviewed the Rails 3 guides on the JQuery-File-Upload site, but they assume it's a singular model, so it's all built around a form. Does anyone have any examples of their implementation or is there an existing tutorial that I haven't yet stumbled across?

I'm sure someone has had a similar issue... is JQuery-File-Upload to appropriate tool or should I look at something else?

Edit
Report

1 Answer

1

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

<div id="fileupload" class="image_add">
    <%= form_for Image.new, :html => {:multipart => true} do |f| %>
        <div class="fileupload-buttonbar">
            <label class="fileinput-button">
                <span>Add files...</span>
                <%= hidden_field_tag :project_id, @project.id %>
                <%= f.file_field :image %>
            </label>
            <button type="submit" class="start">Start Upload</button>
            <button type="reset" class="cancel">Cancel Upload</button>
            <button type="button" class="delete">Delete Files</button>
        <
answered 2012-05-18T22:29:35.627

Your Answer