2017-07-07 100 views
4

我正在为用户构建一个应用程序来提交“冒险”,并且我希望设置单独的页面来显示城市冒险。我遵循这个建议(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很陌生,这是我的第一个项目。Ruby on 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

构建自定义路由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 
+0

如果您在'search'方法中重定向,则无需执行搜索并设置分配。除非我误认为那些人会吃一些时间,然后被抛弃。此外,在重定向结束时丢失''' –

+0

@SimpleLime是的,你正在写。它可以在'display_city'方法上完成,取而代之的是 – Pavan

+0

@Pavan会根据城市以外的标准重定向删除当前的搜索能力吗?如果它只能是一个或另一个,你有什么建议以不同的方式显示基于城市参数的冒险列表? – adowns