vise
vise

Reputation: 13373

Namespaced resources

This is an excerpt from my config/routes.rb file:

resources :accounts do |account|

      account.resource :profile, :except => [:new, :create, :destroy]

      account.resources :posts,
                        :collection => { :fragment => :get },
                        :has_many => [:comments, :likes]

      # even more code

end

I would like that each nested resource to be loaded from from the account namespace such as Account::PostsController instead of PostsController.

Using resources :accounts, :namespace => 'account' tries to load AccountPostsController.

Trying to nest the structure doesn't really work all that well:

map.namespace :account do |account|
..
end

The previous code will load the files from the locations I want, however it does add the namespace to the url and the generated paths so I'll have methods such as account_account_posts_url and similar paths.

Another alternative is to use something like:

account.resource :profile, :controller => 'account/profile'

I really don't like this as it involves both code duplication and forces me to remove some of the rails magic helpers.

Any thoughts and suggestions?

Upvotes: 0

Views: 184

Answers (2)

Tony Fontenot
Tony Fontenot

Reputation: 5101

Changing my routes.rb and running rake routes I came up with the following:

map.resources :accounts do |accounts|
  accounts.namespace :account do |account|
    account.resource :profile, :except => [:new, :create, :destroy]
  end
end

This gets you what you want. The correct url and pointing to account/... controller.

See Rails Routing for more detailed info and options on what can be done with Rails Routes.

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107718

So what's specifically wrong with namespacing? I think this is what you're trying to do:

map.namespace :account do |account|
  account.resource :profile
end

This will try to load the controller at app/controllers/account/profiles_controller.rb and will generate routes such as account_profile_path.

Updated based on comment:

map.resources :accounts do |account| 
 account.resource :profile
end

Will give you /accounts/22/profile.

Upvotes: 0

Related Questions