Ruby-on-rails 帮助使用 rails link_to 和 post 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5822423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Help with rails link_to and post methods
提问by nacho10f
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
但是在我的数据库上,它使用 student_id 和 batch_id 为空创建它
回答by fl00r
You are updating exist batch, but not creating, so you should make PUTrequest to updateaction
您正在更新现有批次,但未创建,因此您应该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
回答by brettish
The params hash doesn't contain a :batch_studenthash because you are not submitting from a form. The params has should look something like {"student_id" => 1, "batch_id" => 1, "method" => "post"}.
params 散列不包含:batch_student散列,因为您不是从表单提交。params 应该看起来像{"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.saveto check for errors.
使用 new 的好处是你可以做一个if @batch_student.save检查错误。
I hope this helps.
我希望这有帮助。
回答by pangpang
The parameters and the http method should be together {:batch_id=> b.id, :method=> :post}
参数和http方法要一起 {:batch_id=> b.id, :method=> :post}
<%= link_to "Add", student_batch_students_path(@student), {:batch_id=> b.id, :method=> :post} %>

