Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant Rails: multiple routes, same controller action

What is the most elegant way to have multiple routes go to the same controller action?

I have:

  get 'dashboard', to: 'dashboard#index'
  get 'dashboard/pending', to: 'dashboard#index'
  get 'dashboard/live', to: 'dashboard#index'
  get 'dashboard/sold', to: 'dashboard#index'

This is quite ugly. Any "more elegant" recommendations?
Bonus points for a one liner.

like image 421
dipole_moment Avatar asked Mar 20 '15 19:03

dipole_moment


1 Answers

Why not have just one route and one controller action, and differ the functionality based on params passed to it?

config/routes.rb:

get 'dashboard', to: 'dashboard#index'

app/controller/dashboard_controller.rb

def index
  ...
  if params[:pending]
     # pending related stuff
  end
  if params[:live] 
    # live related stuff
  end
  if params[:sold] 
    # sold related stuff
  end     
  ...
end

links in views

  • pending: <%= link_to "Pending", dashboard_path(pending: true) %>
  • live: <%= link_to "Live", dashboard_path(live: true) %>
  • sold: <%= link_to "Sold", dashboard_path(sold: true) %>
like image 184
Prakash Murthy Avatar answered Nov 05 '22 00:11

Prakash Murthy