Kris MP
Kris MP

Reputation: 2415

Rails 4 routes passing default parameter without having to include it on url

I have this routes in my routes.rb

get "/whats_new/:only_new" => 'products#index', as: :whats_new_page_products, :defaults => { :only_new => true }

and its produces:

localhost:3000/whats_new/true

is there any way to only show it as:

localhost:3000/whats_new/

thanks in advance

Upvotes: 1

Views: 604

Answers (3)

Richard Peck
Richard Peck

Reputation: 76784

#config/routes.rb
get :whats_new, to: "products#index", as: :whats_new_page_products #-> url.com/whats_new

#app/controllers/products_controller.rb
class ProductsController < ApplicationController
   def index
      if /^(whats_new)$/ !~ request.path
        @products = Product.only_new
      else
        @products = Product.all
      end
   end
end

I don't think you need to pass a param to identify the request. The above is slightly hacky, but should work.

Upvotes: 0

umang
umang

Reputation: 251

Try:

get "/whats_new(/:only_new)" => 'products#index', as: :whats_new_page_products

That will create an optional parameter, which you can check for in your controller.

Now users can make requests to /whats_new or /whats_new/true (replace true with any parameter value). In your controller, you can check to see if params[:only_new] is true or not.

Upvotes: 1

Philip7899
Philip7899

Reputation: 4677

You could just do

get ':whats_new' => 'products#index', as: :whats_new_page_products, :defaults => {:whats_new => true }

That should produce the results you want. Just keep in mind in your controller action everytime you had params[:only_new] you'll now need to do params[:whats_new]

Upvotes: 2

Related Questions