A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Ruby on Rails: Multiple file attachments with Carrierwave and Nested_form

First, I would like to thank Luca for this post.

Add in Gemfile

gem "nested_form", :git => 'https://github.com/ryanb/nested_form.git'

Then run

bundle install

and

rails g nested_form:install

In my “parent” model:

class Allergy < ActiveRecord::Base
  validates :name, :presence => true
  has_many :attachments, :dependent => :destroy
  accepts_nested_attributes_for :attachments
end

In my “child” model:

class Attachment < ActiveRecord::Base
  belongs_to :allergy, :polymorphic => true #add polymorphic
  mount_uploader :attachment, AttachmentUploader
end

In my views:

...
<%= nested_form_for [@patient, @allergy], :html => {:multipart => true} do |f| %> 
    <%= render :partial => "fields", :locals => {:f => f} %>
<% end %>
...

and in the partial I have this:

<%= f.fields_for :attachments do |attachment_form|  %>
  <div class="clearfix">
    <%= attachment_form.label :desc %>
    <%= attachment_form.text_field :desc %>
    <%= attachment_form.label :attachment %>
    <%= attachment_form.file_field :attachment %>
    <%= attachment_form.link_to_remove "Remove this attachment" %>
  </div>
<% end %>
<%= f.link_to_add "Add attachment", :attachments %>

And to save in the controller, I have something like this:

def create
...
  @patient = Patient.find(params[:patient_id])
  if @allergy = @patient.allergies.create(params[:allergy])
    # success
  else
    # error handling
  end
end

I might have missed something, but if you have comments, suggestions, and corrections do not hesitate to post them below. I am also very new to Ruby on Rails.

Might be different from what you have but this doc was useful.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>