Rails:如何基于路由渲染同一控制器下的对应视图
同一控制器方法对应不同路由渲染不同视图(无额外URL参数)
首先,先确认你的路由定义没问题,两条路由都指向front_office#search_by_id且设置了路由别名,这是实现需求的基础:
# config/routes.rb match 'compare' => 'front_office#search_by_id', :via => :get, :as => :front_office_compare match 'full_report' => 'front_office#search_by_id', :via => :get, :as => :front_office_full_report
接下来,在front_office_controller.rb的search_by_id方法里,我们可以通过判断当前请求的路由来指定要渲染的视图,完全不需要在URL里加额外参数。这里有两种常用的实现方式:
方式一:使用Rails路由辅助方法(推荐)
利用路由别名生成的辅助方法,结合current_page?来精准匹配路由——这种方式的好处是,以后如果修改路由路径,代码不用跟着手动调整,更符合Rails最佳实践:
# app/controllers/front_office_controller.rb def search_by_id # 先处理你的业务逻辑,比如获取需要展示的数据 # @item = YourModel.find(...) # 根据当前路由判断渲染对应的视图 if current_page?(front_office_compare_path) render :compare elsif current_page?(front_office_full_report_path) render :full_report end end
方式二:直接判断请求路径
如果觉得辅助方法有点绕,也可以直接判断request.path的值,这种方式更直观:
# app/controllers/front_office_controller.rb def search_by_id # 业务逻辑代码... case request.path when '/compare' render :compare when '/full_report' render :full_report end end
最后,别忘了确保对应的视图文件已经创建:
app/views/front_office/compare.html.erb(对应/compare路由的视图)app/views/front_office/full_report.html.erb(对应/full_report路由的视图)
这样设置后,访问/compare就会自动渲染compare视图,访问/full_report则渲染full_report视图,整个URL干净无额外参数,完全符合你的需求。
内容的提问来源于stack exchange,提问作者JudgeProphet
相关产品推荐
相关产品推荐

