Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Custom Route to Rails app

I have read up on the Rails Guides.

What I want to set up are the following routes that are routed to the 'profiles' controller:

GET profiles/charities - Should display all the charities
GET profiles/charties/:id should display a specfic charity
GET profiles/donors - Should display all the donors
GET profiles/donors/:id - Should display a specfic donor

I have created the profile controller and two methods: charities and donors.

Is this all I need?

like image 574
Sriram Venkatesh Avatar asked Oct 16 '13 02:10

Sriram Venkatesh


People also ask

How do you define a route in Ruby?

We have to define the routes for those actions which are defined as methods in the BookController class. Open routes. rb file in library/config/ directory and edit it with the following content. The routes.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.


2 Answers

The following will set up routes for what you want, but will map them to :index and :show of CharitiesController and DonorsController:

namespace :profiles do
  # Actions: charities#index and charities#show
  resources :charities, :only => [:index, :show]

  # Actions: donors#index and donors#show
  resources :donors, :only => [:index, :show]
end

When it's more appropriate to set up custom routes, something like this would do:

get 'profiles/charities', :to => 'profiles#charities_index'
get 'profiles/charities/:id', :to => 'profiles#charities_show'
get 'profiles/donors', :to => 'profiles#donor_index'
get 'profiles/donors/:id', :to => 'profiles#donor_show'

Here are relevant sections in the guide that you were going through:

  1. Resource Routing: the Rails Default - Controller Namespaces and Routing
  2. Non-Resourceful Routes - Naming Routes
like image 64
kristinalim Avatar answered Oct 06 '22 22:10

kristinalim


The charities and donors seem to be nested resources. If so, in your config/routes.rb file you should have something like,

resources :profiles do
  resources :charities
  resources :donors
end

Because these are nested resources, you do not need the two methods named charities and donors in your profiles controller. In fact, depending on your app, you may need separate controllers and/or models for your charities and donors.

like image 30
Chris Jeon Avatar answered Oct 07 '22 00:10

Chris Jeon