2

我有一个应用程序,其父资源 (has_many) 的模式和子资源 (belongs_to) 的片段。我的愿望是为特定页面构建几个自定义路由,我想知道最好的方法。现在,这就是我所拥有的工作,但我想知道是否有更好的方法,因为我阅读的关于自定义路由的文章告诉我这不是一个好习惯。

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

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

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

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

1 回答 1

1

我想嵌套资源是你需要的。您可以只为嵌套指定索引操作,并单独保留所有片段资源。此外,您还需要在操作中添加一些逻辑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模型,你可以像使用片段一样嵌套资源:

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

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

resources :patterns do
  get :images, on: :member
end
于 2014-04-29T19:09:06.960 回答