How to route with optional and ordered parameters in Rails 4?

Asked

Viewed 1,243 times

2

How 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 all available options are not provided, for example:

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

The idenficator would always be the _Something.
And the comma to insert more than one item.

SOLUTION

I believe I can do something even better in the list of available and in the removal, but I’m half 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

1 answer

1


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

As far as I know, there is no way you can identify parameters via route, this should be dealt with in controller.

To make a route of this type, you can resort to the 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 is between relatives are optional, do not need to pass all.

Having the parameters in your controller, then it’s easy to work, use the .split(',') and .split('_') to break the way you wish.

  • Perfect guy, that’s right! I did all the treatment on the controller. I went through the elements, I did the splits, and I set new stops, and I deleted the old stops.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.