I am building a little project in Ruby on Rails (which I am fairly new in using). The idea ist to have a little listing website where users can filter all listings according to country and category.
I realized the filter using the gem ransack and it works.
Now, what I want to improve are the URLs after the user filtered the view, for example my URL looks like this: domain.com/listings?utf8=%E2%9C%93&q%5Bcategory_eq%5D=sport&q%5Bcountry_eq%5D=Bosnia+and+Herzegovina
I would like to have pretty, clean URLs for SEO reasons. The above example would then translate to (or something in this direction): domain.com/listings/all/c/sport/d/Bosnia-and-Herzegovina
I installed the gem rack rewrite and got some basic redirections working. But I can't figure out how the rule needs to be in order to achieve the URL above. Especially because the user could only use one filter which would result in a URL like this: domain.com/listings/all/d/Bosnia-and-Herzegovina
Has somebody an idea or came across the same problem?
You should add something like this to your config/routes.rb
:
get 'listings/all/c/:category/d/:country', to: 'listings#search'
# if you want URLs with only country or only category
# also add these two
get 'listings/all/d/:country', to: 'listings#search'
get 'listings/all/c/:category', to: 'listings#search'
Then in your ListingsController#search method (substitute for your actual controller and method name):
# Let's say user opens "domain.com/listings/all/c/sport/d/Bosnia-and-Herzegovina
def search
params[:category] # 'sport'
params[:country] # Bosnia-and-Herzegovina
# ... you code could use params above ...
end