Rails-复杂和嵌套路线的约定(无资源)

时间:2018-10-22 01:19:03

标签: ruby-on-rails ruby controller routes ruby-on-rails-5

我的应用程序中设置了一些更复杂的路由,我想知道是否可以将其转换为资源丰富的路由。

理想的Rails约定是将它们转换为足智多谋的路线吗?

路线1:/ grandparent-place / parent-place / place /

这些路由位于我的route.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?

1 个答案:

答案 0 :(得分:0)

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

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

在您的设置中,您拥有places作为资源。 因此,在此端点get '/places/:id'中:id指定应撤退的地点。

关于您的第一个路线,最合适的是只留下一个get端点:

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 In

关于助手,没有覆盖或不覆盖路径方法的通用规则,它再次主要取决于应用程序的需求。我认为这是保持它们尽可能完整的一种好习惯。在您的情况下,可以覆盖以下方法,而不是覆盖path方法:

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

在您看来完全一样,例如:

link_to 'MyThredPost', thread_posts_path(thread) + '#post-' + post.id
相关问题