【问题标题】:Custom Route to Custom Page in Rails 4Rails 4中自定义页面的自定义路由
【发布时间】:2014-04-29 14:57:03
【问题描述】:

我有一个应用,其父资源 (has_many) 为 patterns,子资源 (belongs_to) 为 sn-ps。我的愿望是为特定页面构建几个自定义路由,我想知道最好的方法。目前,这是我所拥有的,但我想知道是否有更好的方法,因为我阅读的关于自定义路由的文章告诉我这不是一个好习惯。

我故意不嵌套资源,因为 sn-ps 需要独立存在,并且需要在其父模式的上下文中查看。

目标是能够创建一些自定义视图,如下所示:

http://patterns.dev/patterns/:id/snippets //Got this one working, but incorrectly I believe
http://patterns.dev/patterns/:id/snippets/sort // Show all snippets for pattern to sort
http://patterns.dev/patterns/:id/images // Show all the images for patterns to moderate

routes.rb

Rails.application.routes.draw do

devise_for :users, :path => '', :path_names => {:sign_in => 'login', :sign_out => 'logout'}

resources :patterns
get 'patterns/:id/snippets' => 'patterns#snippets', as: 'pattern_snippets'

resources :snippets

root 'welcome#index'

end

【问题讨论】:

    标签: ruby-on-rails routes custom-routes ruby-on-rails-4.1


    【解决方案1】:

    我猜nested resources 是你需要的。您可以只为嵌套指定索引操作,并单独保留所有 sn-ps 资源。此外,您还要向snippets#index 操作添加一些逻辑以检查params[:pattern_id] 的存在:

    resources :patterns do
      # this line will generate the `patterns/:id/snippets` route
      # referencing to snippents#index action but within specific pattern.
      # Also you have to add pattern_id column to snippets table to define the relation
      resources :snippets, only: :index
    end
    resources :snippets
    

    使用 Collection Routes 让 Rails 能够识别像/patterns/:id/snippets/sort 这样的路径

    resources :patterns do
      resources :snippets, only: :index do
        # this line will generate the `patterns/:id/snippets/sort` route
        # referencing to snippets#sort action but again within specific pattern.
        get :sort, on: :collection
      end
    end
    resources :snippets
    

    如果你有 Image 模型,你可以像使用 sn-ps 一样嵌套资源:

    resources :patterns do
      resources :images, only: :index
    end
    

    如果它只是模式控制器中的一个动作,你可以这样做:

    resources :patterns do
      get :images, on: :member
    end
    

    【讨论】:

    • 这就是我要找的。感谢您花时间写出来。为我节省了大量时间和挫败感!
    猜你喜欢
    • 2015-09-10
    • 1970-01-01
    • 2019-09-03
    • 2018-10-18
    • 2023-03-24
    • 2016-09-28
    • 2011-06-05
    • 2016-01-13
    相关资源
    最近更新 更多