Topic: One of my routes is not working

I have a User model which has_many :portfolios and each Portfolio has_many :pictures.  My routes look like this:

  resources :users do
    resources :portfolios do
      resources :pictures

Then I try to create a new Portfolio like this:

<%= link_to "new portfolio...", new_user_portfolio_path(current_user) %>

With a form like this:

<%= form_for [current_user, @portfolio], html: { class: "form_settings" } do |f| %>
<% end %>

But when I click on "new portfolio..."  my URL says "/users/12/portfolios/new" and I get this error:

Routing Error

No route matches {:action=>"show", :controller=>"portfolios", :user_id=>#<User id: 12, name: "michael", password_digest: "d787f56b080945c1ec0b3343cbf962ca427bb8ef", remember_token: "dL4nPlt0E5azUMemNIvkdg", admin: false, created_at: "2013-03-03 01:18:19", updated_at: "2013-03-03 19:56:28">, :id=>#<Portfolio id: nil, user_id: 12, name: nil, created_at: nil, updated_at: nil>}

Last edited by mikeglaz (2013-03-04 13:18:13)

Re: One of my routes is not working

Ok, figured out a part of it.  My layout file has a toolbar which looks like this:

<% current_user.portfolios.each do |portfolio| %>
  <li><%= link_to, user_portfolio_path(current_user, portfolio) %></li>
<% end %>
<li><%= link_to "new portfolio...", new_user_portfolio_path(current_user) %></li>

Which works when I'm at /users/12 but it breaks when I go to /users/12/portfolios/new.  So my question is why can't I link to the show page of my portfolios from the new page?

Last edited by mikeglaz (2013-03-04 13:23:03)

Re: One of my routes is not working

Post a stack trace from your development.log file
Also including the current user in your params hash for the link is just plain wrong and totally unnecessary. Remove that. It leaves you wide open for security vulnerabilities.
You should have a name spaced route rather than a nested route and use a before filter that requires a user to be logged in. That way you can get the current user within the relevant controller actions. You probably have this setup anyway otherwise the current_user object would not be available to you in the toolbar partial.

Also you might want to wrap those links inside an of current_user  check so that you cater for the condition where there is no current user (like the log in page)

You would probably benefit a lot from watching … om-scratch
There is a revised episode which would be worth subscribing to get.

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)

Re: One of my routes is not working

I figured it out.  I had to add this:

<%= link_to, user_portfolio_path(current_user, portfolio) unless portfolio.new_record?%></li>