我的数据层次结构是'案例'有很多'类别'有很多'任务'
我已经遵循文档,资源永远不应该嵌套超过1级。因此,我使用浅如下:
my routes.rb
resources :cases do
resources :categories, :shallow => true do
resources :tasks, :shallow => true
end
end
佣金路线
category_tasks GET /categories/:category_id/tasks(.:format) tasks#index
POST /categories/:category_id/tasks(.:format) tasks#create
new_category_task GET /categories/:category_id/tasks/new(.:format) tasks#new
edit_task GET /tasks/:id/edit(.:format) tasks#edit
task GET /tasks/:id(.:format) tasks#show
PATCH /tasks/:id(.:format) tasks#update
PUT /tasks/:id(.:format) tasks#update
DELETE /tasks/:id(.:format) tasks#destroy
case_categories GET /cases/:case_id/categories(.:format) categories#index
POST /cases/:case_id/categories(.:format) categories#create
new_case_category GET /cases/:case_id/categories/new(.:format) categories#new
edit_category GET /categories/:id/edit(.:format) categories#edit
category GET /categories/:id(.:format) categories#show
PATCH /categories/:id(.:format) categories#update
PUT /categories/:id(.:format) categories#update
DELETE /categories/:id(.:format) categories#destroy
cases GET /cases(.:format) cases#index
POST /cases(.:format) cases#create
new_case GET /cases/new(.:format) cases#new
edit_case GET /cases/:id/edit(.:format) cases#edit
case GET /cases/:id(.:format) cases#show
PATCH /cases/:id(.:format) cases#update
PUT /cases/:id(.:format) cases#update
DELETE /cases/:id(.:format) cases#destroy
root GET / cases#index
我已将类别视图放入case / show.html.erb以显示此案例中的类别。
案例的网址#show是 localhost:3000 / cases / 9
如果我想创建一个新类别,链接将是 localhost:3000 / cases / 9 / categories / new
它适用于redirect_to案例#show page with my categories#create action
def create
@case = Case.find(params[:case_id])
@category = Category.new(category_params)
@category.case = @case
@case.member = current_member
if @category.save
redirect_to case_path(@case)
else
render :new
end
end
但是当我尝试编辑类别并更新它时
网址更改为 localhost:3000 / categories / 2 / edit 我已经没有case_id了。
它无法重定向回案例#show page localhost:3000 / cases / 9
我尝试将类似的代码编写为我的创建操作,如下所示
def update
@case = Case.find(params[:case_id])
@category = Category.find(params[:id])
@category.case = @case
if @category.update(category_params)
redirect_to case_path(@case)
else
render :edit
end
end
但它无法获取case_id和错误消息,如下所示
Couldn't find Case with 'id'=
如何在编辑和更新“类别”后重定向到 localhost:3000 / cases / 9 ?
答案 0 :(得分:1)
shallow: true
根据document将edit_category
更改为浅路线。浅路线中没有父资源ID。
您可以改用@case = @category.case
。无需category_id
PARAM
答案 1 :(得分:0)
由于您不想在编辑类别时更改大小写,请尝试以下方法。
def update
@category = Category.find(params[:id])
@case = @category.case
if @category.update(category_params)
redirect_to case_path(@case)
else
render :edit
end
end