views:

233

answers:

1

I have two classes:

class User < ActiveRecord::Base
  :has_one :foo
end

class Foo < ActiveRecord::Base
  :belongs_to :user 
end

The Foo is optional.

I created the following routing:

resources :users do
  resources :foo
end

Which results in the following routes:

GET    /users/:user_id/foo(.:format)              {:controller=>"foos", :action=>"index"}
user_foos POST   /users/:user_id/foo(.:format)              {:controller=>"foos", :action=>"create"}
new_user_foo GET    /users/:user_id/foo/new(.:format)          {:controller=>"foos", :action=>"new"}
GET    /users/:user_id/foo/:id(.:format)          {:controller=>"foos", :action=>"show"}
PUT    /users/:user_id/foo/:id(.:format)          {:controller=>"foos", :action=>"update"}
user_foo DELETE /users/:user_id/foo/:id(.:format)          {:controller=>"foos", :action=>"destroy"}
edit_user_foo GET    /users/:user_id/foo/:id/edit(.:format)     {:controller=>"foos", :action=>"edit"}

Questions:

  1. It seems like the Index and Show actions are redundant. Should one of them be removed? If so, which one?
  2. The :id parameter in the Show action seems unnecessary, as user_id is a foreign key in the foos table and there is only one foo per user. Am I mistaken?
  3. I would like to have a graceful way to route to the New action if there isn't a foo. One option would be to test @user.foo.nil? in the FooController's Show or Index action, then redirect to the New action. Is there a better way?

Thanks for your time.

A: 

If your model has a has_one association, try to set up the route using resource :foo (note the singular method name "resource", not "resources"). This will set up a singleton resource route (which e.g. has no index action and member actions don't have an id param since there's only one member). See also http://apidock.com/rails/ActionController/Resources/resource (2.3 documentation, but applies to 3.0 as well afaik).

Andreas
Can't believe that I missed that.
Craig