Marvin Danig
Marvin Danig

Reputation: 3938

How to remove ControllerName from a Rails Resource?

I wish to map new_user path of the user resource to 'ROOT_DOMAIN/new' URL. My routes.rb looks something like this:

  #new_user GET      /users/new(.:format)                        users#new

  # User Resource
  match 'new', :to => 'users#new', via: [:get, :post]
  resources :users do
    collection do
      match 'new', :to => 'users#new', via: [:get, :post]
    end  
  end

So while I'm able to hit the /new URL to the desired action with

  match 'new', :to => 'users#new', via: [:get, :post]

but the new_user path still leads to '/users/new'. How to remove the controller_name from the new_user method?

Upvotes: 2

Views: 48

Answers (1)

Mandeep
Mandeep

Reputation: 9173

Your new_user_path takes you to user#new because that's how rails build resourceful routes. Have a look at rails guides to learn more. You need to pass the as: option to your routes in order to give them proper helper methods like:

post '/home' => "home#index", as: :home

This will give you two helpers home_path and home_url

Now you have

resources :users do
  collection do
    match 'new', :to => 'users#new', via: [:get, :post]
  end  
end

If you do rake routes in your terminal you'll see that new_user helpers are assigned to user#new. You need to give it a different path helper and then assign your new_user helpers to your custom route

resources :users do
  collection do
    match 'new', :to => 'users#new', via: [:get, :post], as: :old_new_user
  end  
end

and then you can use your new_user helper for your custom route

match 'new', :to => 'users#new', via: [:get, :post], as: :new_user 

You can check your path helper by doing rake routes in terminal

Upvotes: 1

Related Questions