0

In my application I have users, and then each user has one mailbox where they're delivered messages. My routes.rb looks something like:

  resources :users do
    resources :mailboxes 
  end

If I do a rake route, I see this route available to me:

user_mailbox GET    /users/:user_id/mailboxes/:id(.:format)                           {:action=>"show", :controller=>"mailboxes"}

I wanted to link to this path in my application layout, in a sort of toolbar the user finds at the top of the screen.

My view code is:

<%= link_to image_tag("mail_icon.png", :id => 'mail_notice'), user_mailbox_path(current_user)%>

The problem I'm having is that I get a routing error for this path if I'm nothing withing users/* - So anywhere else in my application besides the resource my mailbox is nested under. If I'm on, lets say my user's index page, the path does work without issue.

No route matches {:action=>"show", :controller=>"mailboxes",

Is there something I could be missing with this route? Anything related to users works, it's just the mailbox that I'm having issues with.

Thanks

2 Answers 2

2

It sounds like mailbox should be a singleton resource.

resources :users do
  resource :mailbox
end

Otherwise it would expect that a user has multiple mailboxes and you'd have to provide the mailbox_id to user_mailbox_path as well.

user_mailbox_path(current_user, @mailbox)
Sign up to request clarification or add additional context in comments.

1 Comment

Doh, thanks a ton for the help. Probably the 2nd or 3rd time I've messed that up over the last few months. Shame on me. I appreciate it.
2

As you can see from the route:

user_mailbox GET    /users/:user_id/mailboxes/:id(.:format)

you need to provide two ids, the :user_id and the :id of the mailbox. This makes sense if the user can have several mailboxes.

<%= link_to image_tag("mail_icon.png", :id => 'mail_notice'), 
            user_mailbox_path(current_user, current_user.mailboxes.first) %>

If you intend the user to have only one mailbox, then I would change the routes.rb like this:

resources :users do
  get :mailbox, :on => :member 
end

and you would get a route like:

mailbox_user   GET    /users/:id/mailbox(.:format)

which would be handled by the mailbox method on UsersController, and you can get the path to it in your views with mailbox_user_path(current_user).

1 Comment

Thanks for the help jorge. Bonehead mistake on my part only passing the user. I truly appreciate the help. I also like the suggestion of using mailbox as just a method to keep things trim.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.