Ruby on Rails: Custom Routes for Search Results

I am creating an application for users to post "adventures," and I would like individual pages to be configured to display adventures in the city. I followed this advice ( Ruby on Rails 4: display search results on the search results page ) so that the search results appear on a separate page, and it works very well, but I would like to do this further and have pre-installed links for routing users in adventures specific to the city. I am not sure how to get results from http://localhost:3000/adventures/search?utf8=%E2%9C%93&search=Tokyoto 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
+4
1

pages. -

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

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

controller#action view .

#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
+1

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


All Articles