5

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
adowns
  • 53
  • 3

1 Answers1

1

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
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • @SimpleLime Yeah, you are write. It can be done on the `display_city` method instead – Pavan Jul 07 '17 at 08:36
  • @Pavan Would redirecting remove the current ability to search based on criteria other than city? If it can only be one or the other, do you have any suggestions on a different way to display a list of adventures based on the city param? – adowns Jul 07 '17 at 10:39
  • 1
    @adowns If you want to keep the search other than city, then you require multiple `params` from the search. Like if you are applying any filter, then those `params` should come as `params[:filter]`. Or you can tweak the form to send the city `params` separately like `params[:city]`. – Pavan Jul 07 '17 at 10:45
  • 1
    @Pavan Thank you! I didn't know about filters. This sounds promising. How do I give you credit for pointing me in the right direction?? – adowns Jul 07 '17 at 11:10
  • 1
    @Pavan nevermind! I just noticed the check mark and "up" mark. – adowns Jul 07 '17 at 11:20