Skip to content

Instantly share code, notes, and snippets.

@jasonlyles
Created March 29, 2012 01:54
Show Gist options
  • Save jasonlyles/2232401 to your computer and use it in GitHub Desktop.
Save jasonlyles/2232401 to your computer and use it in GitHub Desktop.
FORM
= form_for @trip do |f|
%p
= add_paddler_kayak_link("Add a paddler", f)
.actions
= f.submit 'Save'
PADDLER_KAYAK PARTIAL
%p.fields
= select_tag "paddler_kayak[paddler][]", options_from_collection_for_select(@paddlers, "id", "name"), :prompt => "Select Paddler"
= select_tag "paddler_kayak[kayak][]", options_from_collection_for_select(@kayaks, "id", "full_name"), :prompt => "Select Kayak"
= link_to_function "remove", "remove_fields(this)"
TRIP MODEL
class Trip < ActiveRecord::Base
has_many :paddlers
serialize :paddler_kayak, Hash
def self.serialized_attr_accessor(*args)
args.each do |method_name|
eval "
def #{method_name}
(self.paddler_kayak || {})[:#{method_name}]
end
def #{method_name}=(value)
self.paddler_kayak ||= {}
self.paddler_kayak[:#{method_name}] = value
end
"
end
end
serialized_attr_accessor :paddler, :kayak
end
TRIPS CONTROLLER
def create
@trip = Trip.new(params[:trip])
@trip.paddler_kayak = params[:paddler_kayak]
respond_to do |format|
if @trip.save
format.html { redirect_to(@trip, :notice => 'Trip was successfully created.') }
format.xml { render :xml => @trip, :status => :created, :location => @trip }
else
format.html { render :action => "new" }
format.xml { render :xml => @trip.errors, :status => :unprocessable_entity }
end
end
end
TRIP HELPER
module TripsHelper
def add_paddler_kayak_link(name, f)
new_object = Paddler.new
fields = f.fields_for(:paddler_kayak, new_object, :child_index => "new_paddler") do |builder|
render("paddler_kayak")#, :locals => {:f => builder}
end
link_to_function(name, "add_fields(this, 'Paddler', '#{escape_javascript(fields)}')")
end
end
JS
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().children(":first").after(content.replace(regexp, new_id));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment