ruby-on-railsrails-routing

Unable to match custom method REST routes to ruby on rails


I am new to ruby-on-rails and having a hard time trying to get routes to match for my API service.

I designed my custom routes for resources following the Google AIP-136.

For example, for the following routes

In config/routes.rb, I expected the following to work -

post '/books/:id/\:doSomething', to: 'books#do_something_handler'
post '/books/:id/\:doSomeOtherThing', to: 'books#do_some_other_thing_handler'

But this does not work. I get a ActionController::RoutingError (No route matches [POST] "/books/1234:doSomething"):

I tried some other things as well, but did not get a very satisfactory result.

Could someone help me out with how to do this properly.

Using -


Solution

  • Using constraints:

    # POST /books/1:doSomething
    post "/books/:id::custom_method", 
      to: "books#do_something_handler",
      constraint: {custom_method: "doSomething"}
    
    # POST /books/1:doSomethingElse
    post "/books/:id::custom_method",
      to: "books#do_something_else",
      constraints: {custom_method: "doSomethingElse"}
    

    Using rails' action param, in this case custom method would need to match the action name:

    # POST /books/1:doSomething
    # routes to `doSomething` controller action
    post "/books/:id::action", controller: :books
    

    To test:

    <%= form_with url: "books/1:doSomething" do |f| %>
      <%= f.submit %>
    <% end %>
    
    <%= form_with url: "books/1:doSomethingElse" do |f| %>
      <%= f.submit %>
    <% end %>
    

    route with constraints:

    Started POST "/books/1:doSomething" for 127.0.0.1 at 2024-07-26 15:36:50 -0400
    Processing by BooksController#do_something as TURBO_STREAM
      Parameters: {"authenticity_token"=>"[FILTERED]", "commit"=>"Save ", "id"=>"1", "custom_method"=>"doSomething"}
    Completed 200 OK in 3ms (ActiveRecord: 2.3ms | Allocations: 1332)
    
    
    Started POST "/books/1:doSomethingElse" for 127.0.0.1 at 2024-07-26 15:36:52 -0400
    Processing by BooksController#do_something_else as TURBO_STREAM
      Parameters: {"authenticity_token"=>"[FILTERED]", "commit"=>"Save ", "id"=>"1", "custom_method"=>"doSomethingElse"}
    Completed 200 OK in 2ms (ActiveRecord: 0.1ms | Allocations: 892)
    

    route with action param:

    Started POST "/books/1:doSomething" for 127.0.0.1 at 2024-07-26 15:11:22 -0400
    Processing by BooksController#doSomething as TURBO_STREAM
      Parameters: {"authenticity_token"=>"[FILTERED]", "commit"=>"Save ", "id"=>"1"}
    Completed 200 OK in 2ms (ActiveRecord: 0.1ms | Allocations: 1008)