Rails中link_to和post方法的帮助

7

我需要帮助将学生分配到批次中,他们之间存在多对多的关系。

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


我已经在原始帖子中添加了更多细节。 - nacho10f
展示你的 student_batch 动作和路由。 - fl00r
那么为什么它会创建BatchStudent记录?(但是值为空) - nacho10f
不,你的链接是正确的,它应该路由到使用 :method => :post 的 create 方法。params 哈希包含什么?(你的日志/控制台应该显示) - brettish
嵌套路由可以实现这一点,URL 中的 ID 将被提取并放入哈希中。除非它困扰你,否则没有什么特别的问题。 - brettish
显示剩余3条评论
3个回答

22

您正在更新现有的批次,而不是创建新的批次,因此您应该向update操作发出PUT请求。

<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

这完全不是那样的...我想要创建一个BatchStudent...(实质上是将一个新的批次分配给所涉及的学生) - nacho10f
在你的链接中有student_batch_students_path(@student, :batch_id=> b.id),这意味着你已经得到了 b 对象。或者你完全错过了。 - fl00r
当然,我有个b对象...正如你所看到的,在一个表格中,首先显示所有批次,并显示链接以将批次分配给学生。 - nacho10f
哦,你有 BatchStudentStudentBatch 这几个模型 :D - fl00r
好的,这不完全是我最终做的,但它能用。所以我会将其标记为答案。 - nacho10f

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来检查错误。
希望这能有所帮助。

有道理,问题在于它也发送了方法和验证令牌...所以我得到了一个未知属性“method: error”。 - nacho10f
@ignaciofuentes 使用 params.permit(:student_id, :batch_id) 来避免这种情况。 - AmShaegar

-1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接