adowns
adowns

Reputation: 53

Ruby on Rails: Custom routes for search results

I am building an app for users to submit "adventures" and I would like to have individual pages set up to display adventures by city. I followed this advice (Ruby on Rails 4: Display Search Results on Search Results Page) to have search results display on a separate page and that works very well, but I would like to take it further and have pre-set links to route users to city-specific adventures. I'm not sure how to get the results from http://localhost:3000/adventures/search?utf8=%E2%9C%93&search=Tokyo to display on http://localhost:3000/pages/tokyo. Also, I am very new to Rails; this is my first project.

routes.rb

  root 'adventures#index'
  resources :adventures do
    collection do
      get :search
    end
  end

adventures_controller

  def search
    if params[:search]
      @adventures = Adventure.search(params[:search]).order("created_at DESC")
    else
      @adventures = Adventure.all.order("created_at DESC")
    end
  end

Upvotes: 5

Views: 359

Answers (1)

Pavan
Pavan

Reputation: 33542

Build a custom route for pages. something like

get "/pages/:city", to: "pages#display_city", as: "display_city"

and redirect to that with the params[:search]

def search
  if params[:search]
    #this won't be needed here
    #@adventures = Adventure.search(params[:search]).order("created_at DESC")
    redirect_to display_city_path(params[:search])
  else
    @adventures = Adventure.all.order("created_at DESC")
  end
end

Have a controller#action and view for that corresponding route.

#pages_controller

def display_city
  @adventures = Adventure.search(params[:city]).order("created_at DESC")
  ....
  #write the required code
end

app/views/pages/display_city.html.erb
  #your code to display the city

Upvotes: 1

Related Questions