Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with rails link_to and post methods

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

like image 847
nacho10f Avatar asked Apr 28 '11 17:04

nacho10f


Video Answer


2 Answers

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
like image 152
fl00r Avatar answered Sep 22 '22 02:09

fl00r


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.

like image 41
brettish Avatar answered Sep 19 '22 02:09

brettish