【问题标题】:Rails - Conventions for Complex & Nested Routes (non-resourceful)Rails - 复杂和嵌套路由的约定(非资源)
【发布时间】: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


    【解决方案1】:

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

    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

    关于帮助器,没有覆盖或不覆盖路径方法的一般规则,它主要取决于应用程序的需求。我认为尽可能保持它们完好无损是一个好习惯。在您的情况下,您可以放置​​而不是覆盖路径方法:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      相关资源
      最近更新 更多