What is a controller action?
The other half of a route
Rails routes: basics ended with get "partners" => "public/pages#partners", as: :partners, naming a destination without opening it. Here is that destination in this project:
# app/controllers/public/pages_controller.rb, this project's real file (trimmed)
module Public
class PagesController < ApplicationController
def partners
@tiers = ::Partners::Tiers.purchasable
@partners = ::Partners::ActivePartnersQuery.call.partners
@inquiry = ::Partners::Inquiry.new
end
end
end
That's a controller action: an ordinary public method, partners here, in a class that inherits from ApplicationController. The route's "public/pages#partners" string, controller#action, matches it.
One detail is easy to miss: the leading :: on each constant. The class lives inside module Public, so a bare Partners::Tiers makes Ruby look for Public::Partners::Tiers first before falling back to the top level. :: skips that search and starts at the top. In a namespaced controller, copy that on purpose rather than dropping it.
Same shape as every model method already covered
The syntax is no different from Article's published? in ActiveRecord: model introduction; both are ordinary Ruby methods. The role differs. Rails MVC overview named it: a Controller coordinates. Here it asks Partners::Tiers and Partners::ActivePartnersQuery for data and decides no business rules itself.
One route, one action, called once per request
Visiting /partners runs partners once, from the top, on every request, with no state carried over. It's the one-shot execution Rails server & Puma described from the server side: one thread, one request, one pass through the method.
Key takeaways
- A controller action is a public method on a class inheriting from
ApplicationController, matched bycontroller#action. Public::PagesController#partnersis where Rails routes: basics' last example leads.- An action coordinates, asking other objects for data: the Controller role from Rails MVC overview.
- Each request runs its action once, from the top, with no carried-over state.
Keep going with lesson 2
index, show, new, create: four conventional names
The names index, show, new and create carry conventional meanings for listing, displaying, blank forms and saving.
A free account also gives you the quizzes, your progress and notes, and the discussion.