我正在处理嵌套资源项目,并且在我的步骤控制器中出现错误:
def create
@step = Step.new(step_params)
respond_to do |f|
if @step.save
f.html { redirect_to @step, notice: 'Step was successfully created.' }
f.json { render action: 'show', status: :created, location: @step }
else
f.html { render action: 'new' }
f.json { render json: @step.errors, status: :unprocessable_entity }
end
end
end
我得到的错误是:
undefined method `step_url' for #<StepsController:0x007feeb6442198>
我的路线如下:
root 'lists#index'
resources :lists do
resources :steps
end
答案 0 :(得分:14)
在使用嵌套资源时,请按以下步骤更新create操作:
def create
@list = List.find(params[:list_id])
@step = @list.steps.build(step_params) ## Assuming that list has_many steps
respond_to do |f|
if @step.save
## update the url passed to redirect_to as below
f.html { redirect_to list_step_url(@list,@step), notice: 'Step was successfully created.' }
f.json { render action: 'show', status: :created, location: @step }
else
f.html { render action: 'new' }
f.json { render json: @step.errors, status: :unprocessable_entity }
end
end
end
运行rake routes
以查看可用路线。
步骤#show的路线看起来像
GET lists/:list_id/steps/:id steps#show
使用带有2个参数的list_step_url
@list
用于:list_id和@step
for:id转到显示步骤的页面。