I've looked at all the tutorials on how to create multiple objects of
the same type with one form. However, I cannot get it to work with my
REST app. This is what I have tried:
----- Controller ---------
'new' action ----------
def new
@students =
5.times { @students << Student.new }
end
'create' action ----------
params[:students].values do |student|
Student.new(student) unless student.values.all?(&:blank?)
end
-------- View -----------
<% @students.each_with_index do |student, index| %>
<% fields_for "students[#{index}]", student do |s| %>
<%= render :partial => 'students/student_form', :locals =>
{:f => s} %>
<% end %>
<% end %>
I cannot figure out why this is not working. All the student objects
are correctly in the parameters but they will not get saved. Please
help.
def create
params[:students].values do |student|
Student.new(student) unless student.values.all?(&:blank?)
end
respond_to do |format|
if @???.save
flash[:notice] = 'Students were successfully created.'
format.html { redirect_to students_path }
else
format.html { render :action => "new" }
end
end
end
As you can see, since I do not have an instance variable, I don't know
what to put in the if clause. But even if I replace new with create,
it still doesn't create the objects. I've tried getting rid of the
respond_to just to see if the object would be created but no luck.
Finally, I got the objects to save! Here is my new create method:
def create
params[:students].each_value do |student|
@student = Student.new(student) unless student.values.all?
(&:blank?)
@student.save
end
flash[:notice] = 'Family was successfully created.'
redirect_to student_url(@student)
end
Now, as you can see, I had to get rid of my respond_to block. How can
I handle errors using the if clause since the values of @student
change with each object?