Skip to content

Instantly share code, notes, and snippets.

@simaob
Created November 4, 2011 00:40
Show Gist options
  • Save simaob/1338372 to your computer and use it in GitHub Desktop.
Save simaob/1338372 to your computer and use it in GitHub Desktop.
Ruby on Rails - Nested Attributes
<div class="attachment fields">
<%= f.label :caption %>
<%= f.file_field :document %>
<%= link_to_remove_fields "remove", f %>
</div>
<!-- other form code -->
<div class="attachments">
<%= f.fields_for :attachments do |attachment_form| %>
<%= render 'attachment_fields', :f => attachment_form %>
<% end %>
</div>
<%= link_to_add_fields "Attach a file or an image", f, :attachments %><br />
<!-- other form code -->
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$("div.attachments").append(content.replace(regexp, new_id));
}
module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)", :class => "btn remove danger")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')", :class => "btn")
end
end
class Attachment < ActiveRecord::Base
belongs_to :content
end
class Content < ActiveRecord::Base
has_many :attachments
accepts_nested_attributes_for :attachments, :allow_destroy => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment