More Controller Options

Status Codes and Request Formats

Before we move on to changing our views to be used by these new controllers, let's take a look at a couple more things we'll commonly see inside Rails actions:

Set explicit response header status code

def four_oh_four
  # specific HTTP status code for the response
  render plain: '404 Not Found', status: :not_found
  # Fixnums also work:
  # render plain: '404 Not Found', status: 404
end

Respond to multiple request formats

def greeting
  # respond differently to different formats...
  respond_to do |format|
    # render one response for HTML requests
    format.html { render inline: "<p>Hi!</p>" }
    # render another for JSON requests
    format.json { render json: {greeting: 'Hi!'} }
  end
end

Given a /greeting route to this action:

$ curl localhost:3000/greeting    
<p>Hi!</p>
$ curl localhost:3000/greeting.html
<p>Hi!</p>
$ curl localhost:3000/greeting.json
{"greeting":"Hi!"}

.html is assumed, but if the format is .json we receive the JSON response defined above; also notice that we define a Ruby hash, but Rails converts this into a JSON string for us.

Review

The job of a controller action is to react to a specific kind of HTTP request, gather the appropriate data, and assemble an appropriate HTTP response. For our application this process has mostly involved fetching DB data and using that data in our ERB view templates to create HTML response bodies.

As far as inspecting incoming requests goes, we mostly made use of params, but we actually have access to the entirety of the HTTP request in the request object.

And when it comes to setting the response, we've mostly relied on render to accomplish this, but we also have a response object to more directly interact with the HTTP response we're building to send back to the client.

The reason render, params, and the rest of these methods are available to us is because our Rails controllers inherit from ActionController::Base.

The 7 standard action names for a resource controller are:

  • index
  • show
  • new
  • create
  • edit
  • update
  • destroy

Following this naming convention allows resources calls in your config/routes.rb to neatly match up to your controller actions.

And last but not least, don't forget that instance variables (e.g. @posts) defined in your action will also be available for use inside the view that the action renders.

If we adhere to some conventions pertaining to directory, filename, and naming, Rails will take care of a lot of things for us automatically.

For more resources on Rails controllers, check out: