문제

I have an app with a parent resource (has_many) of patterns and a child resource (belongs_to) of snippets. My desire is to build a couple custom routes to specific pages and I am wondering the best way to do that. For now, here is what I have that is working, but I am wondering if there is a better way since the article I read on custom routing tells me this is not good practice.

I have purposefully not nested the resources because the snippets need to stand alone as well as be viewed within the context of their parent pattern.

The goal is to be able to create a few custom views like the following:

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
도움이 되었습니까?

해결책

I guess nested resources is what you need. You can specify just index action for nesting and keep all the snippets resources separately. Also you are to add some logic to snippets#index action to check params[:pattern_id]'s existance:

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

Use Collection Routes to make Rails to recognize paths like /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

If you have Image model you can nest resources the same way like with snippets:

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

If it's just an action in patterns controller you can do:

resources :patterns do
  get :images, on: :member
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top