我有两个对象,Course和TeacherRight。我使用放置在课程'show'视图中创建了一个TeacherRight。我将course_id作为隐藏字段传递给TeacherRight控制器:
=form_for(@right) do |f|
=hidden_field_tag :course_id, @course.id
%ul
%li=f.collection_select :user_id, User.order(:name)-@course.teachers, :id, :name, include_blank: false
%li=f.submit
控制器:
class TeacherRightsController < ApplicationController
def create
course = Course.find(params[:course_id])
@teacher_right = course.teacher_rights.build(teacher_right_params)
@teacher_right.save
redirect_to course
end
private
def teacher_right_params
params.require(:teacher_right).permit(:user_id)
end
#only owner can add teachers to course
def can_edit(course)
redirect_to root_url unless current_user == course.owner
end
它工作正常,但我不能为它编写测试!我写了
class TeacherRightsControllerTest < ActionController::TestCase
def setup
@owner_1 = users(:owner_1)
@course = courses(:course)
@teacher_1 = users(:teacher_1)
end
test "teacher can't add teachers" do
log_in_as(@teacher_1)
assert_no_difference('TeacherRight.count') do
post :create, {teacher_right: {course_id:@course.id, user_id: @teacher_1.id }}
end
end
但是它给出了一个错误:
ActiveRecord::RecordNotFound: Couldn't find Course with 'id'=
app/controllers/teacher_rights_controller.rb:4:in `create'
我可以看到,
post :create, {teacher_right: {course_id:@course.id, user_id: @teacher_2.id, }}
不以控制器可以使用的方式传递course_id。我该如何纠正?
答案 0 :(得分:2)
您不小心在:course_id
哈希中发布了:teacher_right
,因此它会显示为params[:teacher_right][:course_id]
而不是所需的params[:course_id]
。
您的POST请求应如下所示:
post :create, {
course_id: @course.id,
teacher_right: { user_id: @teacher_1.id }
}