帮助rails link_to和post方法

时间:2011-04-28 17:10:32

标签: ruby-on-rails post methods

我需要帮助将学生分配给批次......他们处于多对多的关系中。

        <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>

在我的控制器中

def create
    @batch_student = BatchStudent.new(params[:batch_student])
    @batch_student.save    
  end

我的路线

  resources :students do
    resources :batch_students
  end

resources :batches

但在我的数据库中,它使用student_id和batch_id创建为null

3 个答案:

答案 0 :(得分:21)

您正在更新现有批次,但未创建,因此您应该PUT请求update操作

<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

答案 1 :(得分:2)

params哈希不包含:batch_student哈希,因为您没有从表单提交。 params应该看起来像{"student_id" => 1, "batch_id" => 1, "method" => "post"}

因此,请按如下方式修改您的创建操作:

def create
  @batch_student = BatchStudent.new(params)
  @batch_student.save    
end

# or, a shorter version
def create
  @batch_student = BatchStudent.create(params)
end 

使用new的好处是你可以if @batch_student.save检查错误。

我希望这会有所帮助。

答案 2 :(得分:-1)

参数和http方法应该在一起{:batch_id=> b.id, :method=> :post}

<%= link_to "Add", student_batch_students_path(@student), {:batch_id=> b.id, :method=> :post} %>
相关问题