检测current_page? 在导航部分不工作

这是’shared / subnav’部分的代码。 当我点击链接时,它显示错误No route matches {:action=>"show", :controller=>"location"}但是路由已定义。 我认为下面的代码存在一些问题。

 -if current_page? location_path = link_to 'Edit Location', edit_location_path -if current_page? user_path = link_to 'Edit User', edit_user_path -if current_page? alert_path = link_to 'Edit Alert', edit_alert_path 

这是我的路线

 location GET /locations/:id(.:format) locations#show user GET /users/:id(.:format) users#show alert GET /alerts/:id(.:format) alerts#show 

路线

最重要的是,由于您将路线定义为成员路线,因此您需要确保将相应的ID传递给每个路线:

 #config/routes.rb resources :users, only: [:show, :edit] resources :locations, only: [:show, :edit] resources :alerts, only: [:show, :edit] 

这意味着您必须将:id值传递给任何这些路由 – 可以按如下方式完成:

 user_path("2") 

错误

错误显然是在这里创建的:

 -if current_page? location_path 

如上所述,您需要将有效的“id”传递给路径,以允许它提取所需的对象。 您需要执行以下操作:

 -if current_page? location_path("2") 

但是,更紧迫的是你个人对这些方法的要求。 当然,必须有一种更好的方法来管理这种逻辑的定义方式。 我会尝试以下方法:

帮手

我想我会这样做一个帮手:

 #app/helpers/your_helper.rb Class YourHelper def edit_current(controller, object) current = controller.singularize return link_to "Edit #{current}", eval("edit_#{current}_path(object)") end end 

这应该允许你打电话:

 <%= edit_current(controller_name, @user) %> 

根据您的路线,您没有用于edit位置,用户和警报的操作的路线。 您有show操作的路由,因此为所有三个实体添加edit路由,然后您需要传递要编辑的对象:

 -if current_page? location_path = link_to 'Edit Location', edit_location_path(current_location) -if current_page? user_path = link_to 'Edit User', edit_user_path(current_user) -if current_page? alert_path = link_to 'Edit Alert', edit_alert_path(current_alert) 

current_locationcurrent_usercurrent_alert是您要编辑的对象。

您的路由助手已定义,但期望参数。 例如, edit_user_path期望传递user对象,因此它知道您要编辑哪个用户。

对于用户来说,您可以使用edit_user_path current_user类的东西,但对于其他对象,您可能需要将它们传递给部分对象 。

与current_page比较时,您的show path还需要一些id值。 看看下面的代码,这将解决您的问题。

 -if current_page? location_path(current_location or some id) = link_to 'Edit Location', edit_location_path(current_location or some id) -if current_page? user_path(current_user or some id) = link_to 'Edit User', edit_user_path(current_user or some id) -if current_page? alert_path(current_alert or some id) = link_to 'Edit Alert', edit_alert_path(current_alert or some id)