Rails - 复杂和嵌套路由的约定(非资源)



我的应用程序中设置了一些更复杂的路线,我想知道可以将其变成资源丰富的路线。

将这些变成资源丰富的路线的理想 Rails 约定是什么?

路线1:/祖

父母地点/父母地点/地点/这些路由位于我的 routes.rb 文件的底部,因为它们从根路径拉取,并由父级和子级限定范围。

路线.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

这些路由旨在仅允许特定操作,使用父模块指定控制器目录 - 并使用 # 锚点滚动到指定的帖子。

路线.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?

路径变量用于指定资源,通常一个变量指定一个资源。例如:

get '/publishers/:publisher_id/articels/:article_id/comments/:id'

在您的设置中,您places作为资源。

因此,在此端点中,get '/places/:id':id 指定应检索哪个位置。

关于您的第一个路由,只留下一个获取端点是最合适的:

resource :places, only: [:show] # => get '/places/:id'

并在需要检索父项或祖父项位置时将父项或祖父项的 ID 作为 :ID 传递。这样,您将不需要set_place方法中的任何条件,因此具有:

def set_place
@place = Place.find(params[:id])
end

如果您需要访问某个地方对象的父项或祖父母项,您可以构建:

get '/places/:place_id/parents/:parent_id/grandparents/:id'

或者只是离开get '/places/:place_id/parents/:id',每当您需要访问祖父母时,只需从您的父母位置而不是孩子开始拨打电话。路线设置可能因您的需求而异。Rails提供了关于这个问题的各种例子:

Rails Routing from the Outside from the Outside(英语:Rails Routing from the Outside(关于帮助程序,没有覆盖或不覆盖路径方法的一般规则,同样,这主要取决于应用程序的需求。我认为尽可能保持它们完好无损是一种很好的做法。在您的情况下,您可以放置以下位置,而不是覆盖路径方法:

thread_posts_path(thread) + '#post-' + post.id # => /threads/7/posts#post-15

直接在您的视图中,例如:

link_to 'MyThredPost', thread_posts_path(thread) + '#post-' + post.id

最新更新