I’m trying to define a custom post action in a controller, but I’m having some questions.
This is my controller:
module Api
module V1
class ExamplesController < ApplicationController
def create_a
...
end
def create_b
...
end
end
end
end
I want both actions/methods to be post actions. This is what I have in my routes file:
namespace :api do
namespace :v1 do
match 'examples/create_a', :controller => 'examples', :action => 'create_a'
match 'examples/create_b', :controller => 'examples', :action => 'create_b'
end
end
I can reach these two methods via get requests, but I’d like to trigger them based on an http post. Also, if I check via rake routes it does not tell me if it’s a GET, PUT, POST, etc. method. It’s just blank. How do I tell a route that it’s supposed to be a post method?
And how would a post request in the browser look like to my method?
url: http://localhost:3000/api/v1/examples/create_a.json/create_a
header: Content-Type: application/x-www-form-urlencoded
data: paramA=45¶mB¶mC
Is this the proper URL pattern to do a post to my controller action create_a?
Generally you use
matchwhen you want to map some kind of logical name to a RESTful route and/or to create an alias for a RESTful route. What you’re doing withmatchis fine (in the sense that it will work), but you’re just missing a small thing (which I’ll so you later).First, let’s look at a typical use for
matchcreating an alias for a route:This route lets you use an application path of
/profiletoshowauserinstead of the path/users/:id.Since your code isn’t mapping one name to another, you don’t need a
matchrule. Your use ofmatchadds duplication to your code that isn’t necessary, and usingmatchin the case you presented is more verbose than necessary. Here’s an example of how you could write your API routes withoutmatch, specifying that they are accessible viapostonly:And here’s an example with
match, adding the:viaparameter (which is what you’re missing in your code example) to specify the HTTP verb:Note the duplication of code here. Since you’re not mapping one path name to another you’ve typed your identically named paths twice when compared to the non-
matchversion.You’ll also note that I took out the
:controllerandactionparameters when compared to your original example code, as Rails will infer this automatically when you use the form: