I’m using Prototype to allow the user to add form fields dynamically.
However, each field is the same model over and over again (think of it
as allowing the user to create a lot of Blog posts at once). So I’m
unable to use accepts_nested_attributes_for, since each blog is its
own row in the database. No biggie though because I’m able to give
each blog its own ID using javascript and the getTime function.
But, I can’t figure out how to get my Blog controller to accept these
new dynamically generated form fields. I’m using each_with_index to
properly create unique ID’s for each blog (I know there are newer
ways, but can’t seem to get those to work, and anyway, I don’t think
that’s the problem).
Currently, I have:
def new
@blogs = Array.new(1) {Blog.new}
end
def create
@blogs = params[:blogs].values.collect { |blog|
current_user.blogs.build(blog) }
if @blogs.all?(&:valid?)
@blogs.each(&:save!)
redirect_to user_profile_path(current_user.username)
else
render :action => ‘new’
end
end
This produces one blog entry form by default, and when I submit it, it
gets added perfectly. (If I increase the default to 3 or something,
all those get submitted as well). However, the ones I add using my
Javascript do not. The javacript ID’s are formatted correctly and
everything is correct when I inspect them in Firebug, but these new
fields are not submitted with the form.
What am I doing wrong?
Is it because I’m limiting the array to 1? but allowing the user to
add more? Is there a way to allow Array to accept any and all, but
only display 1 by default?
Any ideas on this are seriously appreciated.