Ruby on Rails:搜索结果的自定义路线

时间:2017-07-07 08:16:40

标签: ruby-on-rails ruby

我正在构建一个应用程序供用户提交"冒险"我想设置单独的页面来显示城市的冒险经历。我遵循了这个建议(Ruby on Rails 4: Display Search Results on Search Results Page),将搜索结果显示在一个单独的页面上,并且效果非常好,但我希望更进一步,并预先设置链接,将用户路由到特定城市的冒险。我不确定如何将http://localhost:3000/adventures/search?utf8=%E2%9C%93&search=Tokyo的结果显示在http://localhost:3000/pages/tokyo上。另外,我对Rails很新;这是我的第一个项目。

的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

1 个答案:

答案 0 :(得分: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#actionview

#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