Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Routes with or without :id

Is there a way to have a route allow an :id or a nil?

For example:

match 'product_specs/:id' => 'home#product_specs', 
      :as => :product_specs, 
      :via => :get

takes the id as a param. But I'd also like to pass an empty param like this product_specs_path() so that I can also have the option of loading all my records.

Is there a routes match that can achieve this?

like image 318
that_guy Avatar asked Feb 24 '23 04:02

that_guy


1 Answers

perhaps if you use the optional parameter as

# Routes
match 'product_specs/(:id)' => 'home#product_specs'

# Controller
def product_specs
  if params[:id].nil?
    product_specs = ProductSpecs.all()
  else
    product_specs = ProductSpecs.find(params[:id])
  end

Would something like that work?

like image 89
Devin M Avatar answered Feb 26 '23 23:02

Devin M