R – New Action Not Working


I have a standard User controller with the normal set of actions (index, show, new, edit, etc) and I'm trying to add a new action named 'profile'. I added the following code:

def profile
    @user = User.find(session[:user_id])

I also created a new view for the action (app/views/users/profile.html.erb), but whenever I try to view that page I get an error:

ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User with ID=profile

Apparently it's hitting the show action. I'm guessing that means I need to add something to my routes to make this work, but I don't know what. So far I just have the two default routes and the map.root line which I uncommented:

map.root :controller => "home"
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

So really I have two questions:

  1. What do I have to do in order to enable my new action?
  2. Why don't the existing routes cover this situation? Other urls consisting of just the controller and action work just fine (e.g. http://localhost:3000/users/new). Why not this one? Shouldn't it just evaluate to :controller = users, :action = profile, :id = nil?

Best Solution

Try putting something like this in your routes.rb file:

map.user_profile '/users/:id/profile', :controller => "users", :action => 'profile', :conditions => {:method => :get}

I think possibly the reason it's doing this is because you are not matching either of the defaults, because you are not setting :id (even though it is detecting your action as the id). I don't know what your URL looks like, but I have a feeling that if you tried http://localhost:3000/users/123124124/profile, it MIGHT work, even without the new line in routes.

Related Question