How to make routes with optional and ordered parameters in Rails 4?

2

How do I make a route like this?

site.com/clothing/men/T-Shirts_type/Nike_brand/100-500_price/Red,White,Blue_color/
site.com/clothing/woman/Nike_brand/100-500_price/Red,White,Blue_color/

It should always be in the following order:

site.com/Sex/Type/Brand/Price/Color

Even if you do not know all the available options, for example:

site.com/Type/Color
site.com/Sex/Price

The identifier would always be _something . And the comma to enter more than one item.

SOLUTION

I think I can do something even better in the list of available and removal, but I'm kind of noob still in ruby.

#routes.rb
get '/:clothing/:sex(/:option1)(/:option2)(/:option3)(/:option4)(/:option5)', to: 'test#index'

-

#controllers/test_controller.rb
def index
    # lista as opções disponíveis
    options = [
        params[:option1], 
        params[:option2], 
        params[:option3], 
        params[:option4], 
        params[:option5]
    ].reject(&:blank?)

    # percorre um por um
    options.each do |option_string|
      # faz o split pelo underline
      choices, category = option_string.split("_")
      # define um novo param
      params[category] = choices
    end

    # deletar os params antigos, que não são usados
    params.delete :option1
    params.delete :option2
    params.delete :option3
    params.delete :option4
    params.delete :option5
end
    
asked by anonymous 20.02.2014 / 13:40

1 answer

1

What you want is to pass parameters via controller to the controller .

As far as I know, there is no way for you to do parameter identification via route, this should be handled in controller .

To make a route of this type, you can use match as below:

match "/clothing(/:param1)(/:param2)(/:param3)(.:format) => "clothing#search"

The parameters will be sent as follows:

Parameters: {"param1"=>"ro100-500_price", "param2"=>"Red,White,Blue_color", "param3"=>"100-500_price"}

What's between relatives is optional, do not need to go through.

Having the parameters in your controller , that's easy to work with, use the .split (',') and .split ('_') to break as you wish.

    
24.02.2014 / 12:57