【发布时间】:2018-10-22 01:19:02
【问题描述】:
我在我的应用程序中设置了一些更复杂的路线,我想知道这些路线是否可以变成资源丰富的路线。
将这些变成资源丰富的路线的理想 Rails 约定是什么?
路线 1:/grandparent-place/parent-place/place/
这些路由位于我的 routes.rb 文件的底部,因为它们从根路径中提取并由父母和孩子限定范围。
Routes.rb
get ':grandparent_id/:parent_id/:id', to: 'places#show', as: :grandparent_place
get ':parent_id/:id', to: 'places#show', as: :parent_place
get ':id', to: 'places#show', as: :place
Places_Controller.rb
def set_place
if params[:parent_id].nil? && params[:grandparent_id].nil?
@place = Place.find(params[:id])
elsif params[:grandparent_id].nil?
@parent = Place.find(params[:parent_id])
@place = @parent.children.find(params[:id])
else
@grandparent = Place.find(params[:grandparent_id])
@parent = @grandparent.children.find(params[:parent_id])
@place = @parent.children.find(params[:id])
end
end
Application_Helper.rb
def place_path(place)
'/' + place.ancestors.map{|x| x.id.to_s}.join('/') + '/' + place.id.to_s
end
路线 2:/thread#post-123
这些路由仅允许特定操作,使用父模块指定控制器目录 - 并使用 # 锚点滚动到指定的帖子。
Routes.rb
resources :threads, only: [:show] do
resources :posts, module: :threads, only: [:show, :create, :update, :destroy]
end
Application_Helper.rb
def thread_post_path(thread, post)
thread_path(thread) + '#post-' + post.id.to_s
end
是覆盖应用程序助手中的路由路径的约定,还是有更好的方法来生成正确的 URL 而无需覆盖助手?
【问题讨论】:
标签: ruby-on-rails ruby controller routes ruby-on-rails-5