blob: 68204c189a3a2ef1041a8d3a222c915663eef84d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
== Methods and Actions ==
A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.
[source, ruby]
----------------------------------------------
class ClientsController < ApplicationController
# Actions are public methods
def new
end
# Action methods are responsible for producing output
def edit
end
# Helper methods are private and can not be used as actions
private
def foo
end
end
----------------------------------------------
There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.
As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of ClientsController and run the `new` method. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
[source, ruby]
----------------------------------------------
def new
@client = Client.new
end
----------------------------------------------
The link:../layouts_and_rendering.html[Layouts & rendering guide] explains this in more detail.
ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
|