Routing to a new action of a nested resource

Hi, can anyone help with a routing problem for nested resources:

My models are User (has_one :house) and House (belongs_to :user).

I have a houses_controller and a user_house_controller. house_controller
is for the admin to perform CRUD on houses; so users' CRUD must go
through the user_house_controller.

The resources are nested like so:

map.resources :houses

map.resources :users do |users|
  users.resource :house, :controller => 'user_house'

So after a new user registers I want to send him to the form for the his
house, ie


I'm having trouble with generating this URL programmatically. In my
users_controller I have:

def create
    @user =[:user]) #user registered, now register his
    redirect_to new_gym_url(:user_id => @user)

I know when one has a nested resource then the URL generator takes 2
arguments: The nested-under model and the nested model. So according to
this logic, the URL helper should look like:

new_gym_url(:user_id => @user, :id => house)

But then I will be referring to a house that hasn't been created yet!
When I just use:

new_gym_url(:user_id => @user) or new_gym_url

I get redirected to the houses_controller#new, and I want to use

This is about to drive me nuts; so please explain!

/ Vahagn

PS! Correct url is http://localhost:3000/users/21/house/new


Issue solved!

users.resource :houses, :controller => 'user_house'

instead of:

users.resource :house, :controller => 'user_house'

Apparently the resources are always plural, regardless that a user only
has one house.


Hi Vahagn. Resources don't have to be plural. For example, one of my
apps has users, and when they login, they access their account at this
To do this, I added the following to routes.rb:
  map.resource :account
You just need to make sure that all of your files and classes have
proper pluralisation. Thus, I have AccountsController.

For your question, I would think that you'd need:
  # config/routes.rb
  map.resources :users do |users|
    users.resource :house, :controller => 'user_house'

  # app/controllers/houses_controller.rb
  class HousesController < ApplicationController

In other words, make sure it's "HousesController" and
"houses_controller.rb" (plural), not "HouseController" or
"house_controller.rb" (singular).

Once you have that working properly, you can generate URLs and paths
to a user's house like this:

I hope that helps,

Hi Nick,-

thanks for your comment, I appreciate it. I've worked around the problem
but it is definitely helpful. Previously I thought that pluralization
patterns in the routes file must follow those of the controllers but now
I can see it's not the case - the two things are decoupled and the most
important thing is the proper pluralization of the controllers.

All the best,

Nick Hoffman wrote: