Multiple objects of the same type with one form - REST

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.

‘create’ action ----------
params[:students].values do |student|
Student.new(student) unless student.values.all?(&:blank?)
end

You aren’t saving the Student? Either by calling Student.save after or
using .create instead of .new. I believe.

Regards,
Andrew

Here is my full create method:

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.

Is something like possible with REST?

Everything works perfectly now after I followed this tutorial:
http://www.railsforum.com/viewtopic.php?id=1063

Here is a tip for fellow newbies: Get your model relationships
correct. Read the ActiveRecord chapters in AWDwR thoroughly.

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?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs