Bloomberg
Bloomberg

Reputation: 2367

how to make custom routes in ruby on rails

I have a URL http://localhost:3000/features?feature_group=everyone and i am trying to make the URL http://localhost:3000/features/for-everyone how this can be done through routes.

Upvotes: 2

Views: 125

Answers (4)

Ravindra
Ravindra

Reputation: 150

Try this

get 'features' => redirect('/features/for-everyone?%{params}'), :constraints => lambda{|req| req.params["feature_group"] == "everyone"}

or

redirect('/features/for-everyone?feature_group=%{feature_group}'), :constraints => lambda{|req| req.params["feature_group"] == "everyone"}

I tested both this scenario and its working fine.

Upvotes: 0

Bloomberg
Bloomberg

Reputation: 2367

Okay i am able to do it with the help of constraints

get 'features' => redirect('/features/for-everyone'), :constraints => lambda{|req| req.params["feature_group"] == "everyone"}

get 'features/for-everyone' => "Features#index"

but in the process params["feature_group"] gets lost. So i needed to pass the params in routes using defaults

get 'features/for-everyone' => "Featues#index", :defaults => { :feature_group => "everyone" }

Upvotes: 0

Shahzad Tariq
Shahzad Tariq

Reputation: 2857

You can define desired route as

get '/features/:feature_group' => 'features#index'

So in action, params[:feature_group] will have 'analytics' in your case

Or you may use collection routes e.g.

 resources :features do
   collection do
     get :feature_group
   end
 end

So you need a feature_group action in your features controller. To learn about rails routing, ref to http://guides.rubyonrails.org/routing.html

Upvotes: 2

Antoine
Antoine

Reputation: 569

Personally I would use your initial feature route leading to your index controller and do a nested route within it using a collection for example:

 resources :features do
    collection do
      get :feature_group
      get :feature_xxxxx
    end
  end

What is cool is that in your controller you can do if params[:feature_group] is nil? or present? or equal to "some words" render your index page with different records or else depending on what you want to do.

Upvotes: 0

Related Questions