【问题标题】:Why does Rails not recognise project_path为什么 Rails 无法识别 project_path
【发布时间】:2017-03-10 12:26:52
【问题描述】:

我想知道是否有人可以帮助解决这个问题...这让我发疯了。

首先,我对这一切还是很陌生。如果我弄错了一些术语,请道歉。我已经完成了一些教程,现在正在开发我的第一个应用程序,没有任何指导性演练......进展缓慢:)

我有两组页面,一组我应该显示侧边栏,另一组不需要它。以下是我的路线...

Rails.application.routes.draw do

#----Pages----
root 'pages#home'
get '/home', to: 'pages#home'
get '/contact', to: 'pages#contact'

#----Users----
get '/app', to: 'users#app'
get 'users/new', to: redirect('/signup')
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'

#----Sessions----
get      '/sessions/new', to: 'sessions#new'
get    '/login',   to: 'sessions#new'
post   '/login',   to: 'sessions#create'
delete '/logout',  to: 'sessions#destroy'


#----Projects----


#----Hazards----


#----Resources----
resources :users
resources :projects
resources :hazards
end

我的标头中有以下代码,可以正常工作...

<% if current_page?(app_path) ||
            current_page?(users_path) ||
            current_page?(projects_path) ||
            current_page?(hazards_path)
    <%= render 'layouts/sidebar' %>
<% end %> 

它为上面列出的路径提供侧边栏,而不是其他路径。但是...我希望从“project_path”添加到上面的页面列表中,所以 /projects/6 等。为了实现这一点,我在上面的代码中添加了以下行...

current_page?(project_path(:id)

导致...

<% if current_page?(app_path) ||
            current_page?(users_path) ||
            current_page?(projects_path) ||
            current_page?(hazards_path) ||
            current_page?(project_path(:id)) %>
    <%= render 'layouts/sidebar' %>

<% end %>

添加后,应用程序加载正常,但侧边栏未添加到项目页面。所以我尝试了另一种方法如下...

current_page?(project_path(@project))

此次修改后,项目页面现在可以正确显示侧边栏,但是...所有其他没有侧边栏的页面无法加载并出现以下错误...

No route matches {:action=>"show", :controller=>"projects", :id=>nil}    missing required keys: [:id]

我束手无策……我也试过了

current_page?(project_path(params.permit))
Current_page?(project_path(project))
current_page?(project_path(project(params[:id])))

有人可以让我摆脱痛苦吗...这不是夸张...纯粹的痛苦。

非常感谢。

【问题讨论】:

    标签: routes conditional ruby-on-rails-5


    【解决方案1】:

    嗯,其他页面没有@project。也许,你可以这样做:

    current_page?(projects_path) ||
    @project && current_page?(project_path(@project)) ||
    ...
    

    【讨论】:

    • *** 在此处输入脏话*** 有效...你能解释一下为什么有效但原来的 project_path(@project) 无效吗?
    • @MysticChimp:它的工作原理是不在没有@project 的页面上输入项目路径检查。术语是“短路”。如果您有兴趣,请阅读它。
    • @MysticChimp:两天是什么意思? :)
    • 这就是我搜索、写作、重写、一般拔头发等多长时间了。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2021-04-27
    • 2020-01-27
    相关资源
    最近更新 更多