Topic: Why do some routes not have names?

Hi everyone!

I'm working on a project that has this in routes.rb (an excerpt):

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :users, :only => [:show, :create, :update] do

        resources :likes, :only => [:create] do
          collection do
            delete :destroy
          end
        end

      end
    end
  end
end

This results in "rake routes" including this:

api_v1_user_likes  DELETE  /api/v1/users/:user_id/likes(.:format)  api/v1/likes#destroy
                             POST      /api/v1/users/:user_id/likes(.:format)  api/v1/likes#create


Why doesn't the create url have a name?

I want to use a URL helper to generate a URL I can post to like this:
api_v1_user_likes_url(:user_id => 4, :listing_id => 51)


--- so my first thought was to add the create route myself:

        resources :likes, :only => [:create] do
          post :create
          collection do
            delete :destroy
          end
        end

This has an odd effect:

api_v1_user_like_create     POST     /api/v1/users/:user_id/likes/:like_id/create(.:format)  api/v1/likes#create
api_v1_user_likes         DELETE /api/v1/users/:user_id/likes(.:format)                 api/v1/likes#destroy
                        POST     /api/v1/users/:user_id/likes(.:format)                 api/v1/likes#create

It creates an *additional* create route, with a like_id, which I don't want, since I am creating a 'like'.

I really just want to give a name to that nameless POST route.

Any ideas?

Last edited by lesliev (2012-11-16 03:35:23)

Re: Why do some routes not have names?

To use the create action just call the url api_v1_user_likes_create etc
You might find this usefull it explains routes in great detail http://guides.rubyonrails.org/routing.html

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)

Re: Why do some routes not have names?

Actually the #create URL is the same as the #destroy URL, only the HTTP verb differs. I assume the URL name is not listed twice to make the display clearer, though if it were listed twice I think I would have figured things out sooner.

For anyone else having this problem, the POST URL I was looking for is also api_v1_user_likes - I just need to POST to it to get the #create action to run.