Routes with optional parameters in Rails

I am trying to set up a route that looks like this: acme.com/posts/:category/:status . Both :category and :status are optional. I wrote a lot of variations, but no one worked:

 resources :posts do match '(/:category)(/:status)', to: 'posts#index', as: 'filter', on: :collection end # Category Links link_to "Questions", filter_posts_path(:questions) link_to "Suggestions", filter_posts_path(:suggestions) # Status Links link_to "Published", filter_posts_path(params[:category], :published) link_to "Draft", filter_posts_path(params[:category], :draft) 

The idea is to be able to: 1) filter by category, 2) filter by status, and 3) filter both by category and by status, if available. The current setting also violated my path /posts/new , always redirecting to posts#index .

+4
source share
4 answers

You can use more RESTful resources :posts (in config / routes.rb) and send the parameters to the query string.

With this approach, all parameters are optional, and you are not limited to using predefined parameters.

+1
source

I had this variation and it looks fine:

  namespace :admin do resources :posts, :except => [:show] do collection do get "/(:category(/:status))", to: "posts#index", as: "list", :constraints => lambda{|req| req.env["PATH_INFO"].to_s !~ /new|\d/i } end end end 

= CONTROLLER = admin / posts rake route

 list_admin_posts GET /admin/posts(/:category(/:status))(.:format) admin/posts#index 
+1
source

Does this work for you?

 resources :posts do collection do match '/:category(/:status)', to: 'posts#index', as: 'filter' match '/:status', to: 'posts#index', as: 'filter' end end 

Hope this helps!

0
source

You can try something like this:

 match '/filter/*category_or_status' => 'posts#index', as: 'filter' 

With this, you can create your own filter path. You can then parse params[:category_or_status] in your controller and get the category or status if specified.

0
source

Source: https://habr.com/ru/post/1442151/


All Articles