这里是rails的新手,
我理解错误,但我不知道为什么我的测试没有通过。我也不知道如何查看传递给动作的params哈希,所以调试对我来说有点混乱。
测试失败错误
1) SectionsController PATCH #update with valid attributes finds the correct course.section assigns @section
Failure/Error: patch :update, course_id: @section.course_id, id: @section.id
ActionController::ParameterMissing:
param is missing or the value is empty: section
# ./app/controllers/sections_controller.rb:52:in `section_params'
# ./app/controllers/sections_controller.rb:36:in `update'
# ./spec/controllers/sections_controller_spec.rb:95:in `block (4 levels) in <top (required)>'
测试
describe "PATCH #update" do
context "with valid attributes" do
before :each do
@course = create(:course)
@section = create(:section, name: "section1")
end
it "finds the correct course.section & assigns @section" do
patch :update, course_id: @section.course_id, id: @section.id
expect(assigns(:section)).to eq(@section)
end
end
end
部分控制器更新方法
def update
@course = Course.find(params[:course_id])
@section = Section.find(params[:id])
if @section.update_attributes(section_params)
flash[:success] = "the section has been updated"
redirect_to [@course, @section]
else
flash[:error] = "you must enter the correct information"
render action: "edit"
end
end
private
def section_params
params.require(:section).permit(:name, :course_id)
end
end
路线
resources :courses do
resources :sections
end
模型
class Section < ActiveRecord::Base
belongs_to :course
validates :name, :course_id, presence: true
end
class Course < ActiveRecord::Base
has_many :sections
accepts_nested_attributes_for :sections
validates :name, presence: true
end
感谢您的帮助!
答案 0 :(得分:4)
使用所有必需参数进行发布的正确方法如下:
post :update, course_id: @section.course_id, id: @section.id, section: {name: @section.name,course_id: @section.course_id}