Ruby rails: url helpers

From wikinotes

The most horrible/evil part of rails is it's url-helper.
Once you get used to it, it's fine I guess. Burn this into back of your eyelids or suffer.

  • unavailable in tests (you must successfully reach your controller to be able to attempt to reach your controller)
  • confusing naming convention order ${verb}_${namespace_and_path}
  • the same naming convention is resolved differently depending on the HTTP method used


Documentation

intro docs (spread across page) https://guides.rubyonrails.org/routing.html#path-and-url-helpers documentation
api docs


URL Helpers

Availability

Available from:

  • controller
  • view

Not Available from:

  • controller tests

Token Order

The path helper logic

${controller}_path                          # /controller#index

${action}_${controller}_path                # /controller#action
${action}_${controller}_path(:id)           # /controller/:id/action

${action}_${namespace}_${controller}_path  # /namespace/controller#action

The same applies to the url helper, which includes the scheme and domain.

${action}_${controller}_url                 # https://domain.com/controller#action

HTTP method mapping to Actions

This only affects resource paths (index, create, show, delete, update).

get       ${controller}_path  # /controller#show
post      ${controller}_path  # /controller#create
patch/put ${controller}_path  # /controller#update
delete    ${controller}_path  # /controller#desstroy

Test URL Helpers

Availability

  • ActionController::TestCase

Token Order

These helpers drop the prefix with the action.

${controller}_path                       # /controller
${controller}_${nested_controller}_path  # /controller/nested_controller

${controller}_url(:id)                   #