I\'m using ryan bates\' plugin nested_form and i have been trying to write my form for a has_many :through relationship.
I have 3 models:
Profile
Updated for latest version of nested_form
https://gist.github.com/stuartchaney/7274894
As I saw here on StackOverflow with another question, I need to nest the hm => t like so
= f.fields_for :memberships do |mem|
= mem.fields_for :organisation do |org|
.row
.span5.org_name
= org.input :name, :label => "<strong>Name of the Organization</strong>"
.span5
= mem.input :title, :label => "<strong>Title in the Organization</strong>"
.row
.span5
= mem.input :starting_year, :label => "<strong>Starting Year</strong>"
.span5
= mem.input :ending_year, :label => "<strong>Ending Year</strong>"
.row
.span10
= org.text_area :description, :label => "<strong>Description of Organisation</strong>"
= mem.link_to_remove "Remove this oranisation"
= f.link_to_add "Add an organisation", :memberships
BUt with Ryan Bates' plugin, the association to memberships organisations is not built as far as i can tell, so i created a new method like this:
= f.link_to_add_hmt "Add an organisation", :organisation, :memberships
And then I pretty much just copied Ryan Bates' plugin verbatim adding a new parameter adding 2 lines below
def link_to_add_hmt(*args, &block)
options = args.extract_options!.symbolize_keys
association = args.pop
association_two = args.pop
options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
options["data-association"] = association
args << (options.delete(:href) || "javascript:void(0)")
args << options
@fields ||= {}
@template.after_nested_form(association) do
model_object = object.class.reflect_on_association(association).klass.new
model_object.send(:"build_#{association_two}")
output = %Q[<div id="#{association}_fields_blueprint" style="display: none">].html_safe
output << fields_for(association, model_object, :child_index => "new_#{association}", &@fields[association])
output.safe_concat('</div>')
output
end
@template.link_to(*args, &block)
end
Look for the references to "association_two". This works great!