Help with rails link_to and post methods

I need help appointing students to parties. They are in many ways.

<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 in my database, it creates it with student_id and batch_id as null

+4
source share
3 answers

You are updating an existing package but not creating it, so you should make a PUT request 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 
+20
source

The params hash does not contain the hash :batch_student because you are not submitting it from the form. The parameters should look something like {"student_id" => 1, "batch_id" => 1, "method" => "post"} .

So, change the action of your 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 that you can do if @batch_student.save to check for errors.

Hope this helps.

+2
source

The parameters and the http method must be together {:batch_id=> b.id, :method=> :post}

 <%= link_to "Add", student_batch_students_path(@student), {:batch_id=> b.id, :method=> :post} %> 
0
source

All Articles