我正在构建一个应用程序供用户提交“冒险”,我希望设置单独的页面来显示城市的冒险.我按照这个建议(
Ruby on Rails 4: Display Search Results on Search Results Page)将搜索结果显示在一个单独的页面上并且运行良好,但我想进一步采取预先设置的链接,将用户路由到特定城市的冒险.我不知道如何从http:// localhost:3000 / adventures / search?utf8 =✓& 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
最佳答案 为页面构建自定义路由.就像是
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
有一个控制器#动作并查看相应的路径.
#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