Reputation: 2929
I have cocoon working with nested form, if you click add field link it inserts input fields. How do I render first input automatically, and then insert additional inputs when "add field" is clicked ?
Upvotes: 5
Views: 2027
Reputation: 678
The quick and dirty solution is to just use jQuery (which Cocoon requires anyways) to click Cocoon's "add item" button when the page loads:
$(document).ready(function() { $(".add_fields").click() } );
I use this in my "new" views, but not in "edit" views, since there may already be some nested items and I don't want to make assumptions. But you could also use script to count the nested item forms and conditionally show the "new item" fields.
Upvotes: 1
Reputation: 4687
In your controller, use this code. In the code below, jobs is a model and profile accepts_nested_attributes_for jobs. Replace @profile with whatever your form is for. The 2nd line is what will build the form fields, unless form fields already exist.
def new
@profile = current_user.profile
1.times {@profile.jobs.build} unless current_user.profile.jobs.any?
end
You may need to change times to time since its singular. In fact, you may be able to get rid of the times method altogether and do:
def new
@profile = current_user.profile
@profile.jobs.build unless current_user.profile.jobs.any?
end
Upvotes: 7