I need help assigning students to batches.. they are in a many to many relation.
<tbody>
<% Batch.all.each do |b|%>
<tr>
<td><%= b.course.name%></td>
<td><%= b.name %></td>
<td><%= b.section_name%></td>
<td><%= link_to "Add", student_batch_students_path(@student, :batch_id=> b.id), :method=> :post%></td>
</tr>
<%end%>
</tbody>
In my controller
def create
@batch_student = BatchStudent.new(params[:batch_student])
@batch_student.save
end
My routes
resources :students do
resources :batch_students
end
resources :batches
But on my database it creates it with student_id and batch_id as null
You are updating exist batch, but not creating, so you should make PUT
request to update
action
<td><%= link_to "Add", student_batch_students_path(@student, :batch_id => b.id), :method=> :post %></td>
def create
@student = Student.find(params[:id])
@batch = Batch.find(params[:batch_id])
@batch_student = BatchStudent.new(:params[:batch_student])
@batch_student.student = @student
@batch_student.batch = @batch
@batch_student.save
end
The params hash doesn't contain a :batch_student
hash because you are not submitting from a form. The params has should look something like {"student_id" => 1, "batch_id" => 1, "method" => "post"}
.
So, modify your create action as follows:
def create
@batch_student = BatchStudent.new(params)
@batch_student.save
end
# or, a shorter version
def create
@batch_student = BatchStudent.create(params)
end
The advantage of using new is you can do a if @batch_student.save
to check for errors.
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With