2

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?

Freebian
  • 107
  • 11

1 Answers1

2

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
EugZol
  • 6,476
  • 22
  • 41
  • Hello EugZol, thanks for your answer. I came one major step forward but I can't put the params to the actual page, because it seems that my params are a two dimensional array? --- !ruby/hash:ActionController::Parameters utf8: "✓" q: !ruby/hash:ActionController::Parameters category_eq: odit country_eq: Bosnia and Herzegovina controller: listings action: index – Freebian Aug 04 '15 at 13:23
  • How specifically are you trying to put params to the actual page? – EugZol Aug 04 '15 at 13:38
  • Controller: "@search = Listing.search(params[:q])" "@listings = @search.result.paginate(:page => params[:page])" – Freebian Aug 04 '15 at 13:42
  • Try `@search = Listing.search(contry_eq: params[:country], category_eq: params[:category])` if you are using new routes I suggested. – EugZol Aug 04 '15 at 13:47
  • You are welcome! You should accept my answer then :) – EugZol Aug 12 '15 at 08:37