Rails 带有额外变量的自定义路径
Rails Custom Path with Extra Variables
我有一个自定义 rails 路由定义如下:
resources :scores, path: "seasons/:season_id/scores/:student_id"
这对我的应用程序很有意义,并且可以使 url 保持标准化。这适用于展示页面,我可以正确地抓取 :season_id 和 :student_id 。
但是,当我尝试路由到任何其他页面时,出现错误。我希望新页面和编辑页面是这些路线:
新建
resources :scores, path: "seasons/:season_id/scores/:student_id/new"
编辑
resources :scores, path: "seasons/:season_id/scores/:student_id/:id/edit"
所以他们仍然遵循正常的约定,这就是当我 运行 rake 路线时发生的情况,但击中任何路线都会抛出:
ActionController::UrlGenerationError
No route matches {:action=>"show", :controller=>"scores", :format=>nil, :id=>nil, :season_id=>#<Score id: ... >, :student_id=>nil} missing required keys: [:id, :student_id]
这在两个帐户上很奇怪。 season id 链接到 score 对象,它表示缺少键。所有键都存在于参数哈希中,这就是我构建链接的方式:
= link_to "Edit", { controller: :scores, action: :edit, id: score.id, student_id: params[:student_id], season_id: params[:season_id]} , class: "btn btn-success btn-xs"
需要嵌套资源时,最好不要使用resources
加path
。它更易于阅读和理解,更不容易出错,并且是 Rails 约定。
你可以这样写你的路线:
resources :seasons do
resources :students do
resources :scores
end
end
然后在您的 link 中使用命名路径方法,如下所示:
link_to "Edit", edit_score_student_season_path(score, params[:student_id], params[:season_id]), class: "btn btn-success btn-xs"
我有一个自定义 rails 路由定义如下:
resources :scores, path: "seasons/:season_id/scores/:student_id"
这对我的应用程序很有意义,并且可以使 url 保持标准化。这适用于展示页面,我可以正确地抓取 :season_id 和 :student_id 。
但是,当我尝试路由到任何其他页面时,出现错误。我希望新页面和编辑页面是这些路线:
新建
resources :scores, path: "seasons/:season_id/scores/:student_id/new"
编辑
resources :scores, path: "seasons/:season_id/scores/:student_id/:id/edit"
所以他们仍然遵循正常的约定,这就是当我 运行 rake 路线时发生的情况,但击中任何路线都会抛出:
ActionController::UrlGenerationError
No route matches {:action=>"show", :controller=>"scores", :format=>nil, :id=>nil, :season_id=>#<Score id: ... >, :student_id=>nil} missing required keys: [:id, :student_id]
这在两个帐户上很奇怪。 season id 链接到 score 对象,它表示缺少键。所有键都存在于参数哈希中,这就是我构建链接的方式:
= link_to "Edit", { controller: :scores, action: :edit, id: score.id, student_id: params[:student_id], season_id: params[:season_id]} , class: "btn btn-success btn-xs"
需要嵌套资源时,最好不要使用resources
加path
。它更易于阅读和理解,更不容易出错,并且是 Rails 约定。
你可以这样写你的路线:
resources :seasons do
resources :students do
resources :scores
end
end
然后在您的 link 中使用命名路径方法,如下所示:
link_to "Edit", edit_score_student_season_path(score, params[:student_id], params[:season_id]), class: "btn btn-success btn-xs"