views:

80

answers:

1

I have a controller with the 7 RESTful actions plus an additional 'current' action, which returns the first active foo record:

class FooController < ApplicationController

  def current

    @user = User.find(params[:user_id])
    @foo = @user.foos.where(:active => true).first

    #use the Show View
    respond_to do |format|
      format.html { render :template => '/foos/show' }
    end

  end

  #RESTful actions
  ...

end

The Foo Model :belongs_to the User Model and the User Model :has_many Foos.

If I structure the routes as such:

resources :users do
  resources :foos do
    member do
      get :current
    end
  end
end

The resulting route is '/users/:user_id/foos/:id'. I don't want to specify the foo :id, obviously.

I've also tried:

map.current_user_foo '/users/:user_id/current_foo', :controller => 'foos', :action => 'current'
resources :users do
  resources :foos
end

The resulting route is more like I would expect: '/users/:user_id/current_foo'.

When I try to use this route, I get an error that reads:

ActiveRecord::RecordNotFound in FoosController#current
Couldn't find Foo without an ID

edit

When I move the current action to the application controller, everything works as expected. The named route must be conflicting with the resource routing.

/edit

What am I missing? Is there a better approach for the routing?

A: 

I think you want to define current on the collection, not the member (the member is what is adding the :id).

try this.

resources :users do
  resources :foos do
    collection do 
      get :current
    end
  end
 end

Which should give you a route like this:

 current_user_foos GET    /users/:user_id/foos/current(.:format)         {:controller=>"foos", :action=>"current"}

Also map isn't used anymore in the RC, it will give you a deprecation warning.

Doon
Somewhat unintuitive, but it worked--thanks. Any thoughts on how to handle the case if a matching foo isn't found? I probably want to show a page that states 'that person doesn't have a foo', rather than routing back to the last page and showing a flash message.
Craig
hmm, hard to say, how does the user get to select a a current foo?. Are you looking at the user, and then click a button / follow a link to look for current foo's assigned to this user? If so I would think going back to the requesting page, with a notice saying, no foos found would be ok..
Doon