Hacker News new | ask | show | jobs
by cmwright 5163 days ago
Would love to see some more information on best practices for routing. I've always used http://guides.rubyonrails.org/routing.html as a go-to resource on routing, and it uses 'match' statements throughout. Is the suggestion here to just change all match statements to the intended REST verb?
2 comments

You should be using resource-based routes if you've already got the RESTful controller thing going.

The match statement is good for the occasional odd cases, but it has an :via option that can be used to restrict which HTTP actions it is allowed to match.

Edit: corrected below...thanks!

Fix - not :as but :via. Using match :via => :post is worse than just post 'data', it is obvious btw :)

and there are almost no odd cases in fact. I would propose special route named "not_found" or "default" like route to be called if no routes found. Nice idea IMO, what do you think?

Thanks, it is early :)

I had to use match when moving from Rails 2 to Rails 3 and parts of the route did not match the controller at all. But I think it was mostly because the upgrade plugin recommended it.

The only thing I don't like about the Rails routing guide is how much it talks about having a default route of `match ':controller/:action/:id'`. I would still use `match`, but any actions that are meant to be posts should add `:method => :post` to them. And ideally use `resources` where ever it makes sense.
You can simply write post instead of match to require a POST request.
You can use most all of the verbs:

   get    '/foo'     => 'foos#index',   as: :foo
   post   '/foo'     => 'foos#new',     as: :new_foo
   get    '/foo/:id' => 'foos#show',    as: :show_foo
   put    '/foo/:id' => 'foos#edit',    as: :edit_foo
   delete '/foo/:id' => 'foos#destroy', as: :destroy_foo
or scope them if you'd like:

    scope controller: "foo", constraints: { id: /0-9]+/ } do
      get    '/foo'   => :index, as: :foo
      post   '/foo'   => :new,   as: :new_foo
      put    ...
      delete ...
    end
Fix: not :method but :via :)

And, again! PLEASE use method "data" instead of match :via => method. It's much better and looks clean.

In exactly what sense do you think that's better?
it does absolutely same job(you can read sources) but requires less symbols and looks RESTful - fair enough, isn't it?
Sorry, you're right about the :via, I must have misremembered.
Right, so what this post is saying is that for the most part the evil is in using this default route, leaving open controller actions that should only be accessible as posts. Will have to look more into the docs, but it's good to know that the methods specified in the guide have some caveats.