How to make resources redirect to another controll

2019-05-23 18:53发布

问题:

I have two models: Book and Magazine. There are few differences in terms of attributes, but i want them to share the same controller and views (the ones of Book's model).

My question is : What is the correct way to set the routes of Magazine model inside routes.rb, considering that Book is already set as following resources :books

This is a basic question, but i want to learn the best way instead of defining all the routes manually one by one

Thanks!

回答1:

You can configure the resource routes to point to a specific controller:

resources :books
resources :magazines, controller: 'books'

This will create the following routes:

                             books GET    /books(.:format)                              books#index
                                   POST   /books(.:format)                              books#create
                          new_book GET    /books/new(.:format)                          books#new
                         edit_book GET    /books/:id/edit(.:format)                     books#edit
                              book GET    /books/:id(.:format)                          books#show
                                   PATCH  /books/:id(.:format)                          books#update
                                   PUT    /books/:id(.:format)                          books#update
                                   DELETE /books/:id(.:format)                          books#destroy
                         magazines GET    /magazines(.:format)                          books#index
                                   POST   /magazines(.:format)                          books#create
                      new_magazine GET    /magazines/new(.:format)                      books#new
                     edit_magazine GET    /magazines/:id/edit(.:format)                 books#edit
                          magazine GET    /magazines/:id(.:format)                      books#show
                                   PATCH  /magazines/:id(.:format)                      books#update
                                   PUT    /magazines/:id(.:format)                      books#update
                                   DELETE /magazines/:id(.:format)                      books#destroy


回答2:

Look into polymorphic relationships some as well, I think ultimately thats where you will end up with this.