Why does Rails not recognise project_path

2019-09-08 09:50发布

问题:

I wonder if anyone can help with this...its driving me crazy.

Firstly I'm still pretty new to all of this. So apologies if I get some terminology wrong. I have completed some tutorials and am now working on my first app without any guided walkthroughs... its slow going :)

I have two groups of pages, one group where I should show a sidebar and one group that does not need it. Below are my routes...

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

I have the following code in my header which works fine...

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

it supplies a sidebar to those paths listed above and not to the others. However... I wish to add to the list above pages from the 'project_path' so /projects/6 etc. To achieve this I added the following line to the code above...

current_page?(project_path(:id)

resulting in...

<% 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 %>

Once added the app loads fine but the sidebar is NOT added to the project page. So I tried an alternative method as follows...

current_page?(project_path(@project))

After this amendment the project page now shows the sidebar correctly but... all other pages that do not have the sidebar fail to load with the following error...

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

I'm at my wits end... I have also tried

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

Can someone please put me out of my misery... thats not an exaggeration... pure misery.

many thanks.

回答1:

Well, the other pages don't have a @project. Perhaps, you could do something like this:

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