Tom Rossi
Tom Rossi

Reputation: 12066

Set Cache-Control Header

Let's say that I have a public/marketing controller and I want to set the response header with Cache-Control: max-age=180, public, must-revalidate

I can't find documentation for setting that at the controller level?

Upvotes: 7

Views: 8156

Answers (1)

Frederik Spang
Frederik Spang

Reputation: 3454

There are a few options that come into mind.

Option 1:

Using expires_in helpers from ActionController::ConditionalGet. These are included in both ActionController::Base and ActionController::API, as far as I remember (http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html).

def some_action
  @some_user_for_view = User.first
  expires_in 3.hours, public: true
end

Option 2:

Setting headers manually with setting #headers on the response object. directly. (http://edgeguides.rubyonrails.org/action_controller_overview.html#the-response-object)

before_action :set_headers

def set_headers
  response.headers["Expires"]='Mon, 01 Jan 2000 00:00:00 GMT'
  response.headers["Pragma"]='no-cache'
  response.headers["Cache-Control"]="no-cache"
  response.headers["Last-Modified"]=Time.now.strftime("%a, %d %b %Y %T %Z")
end

The first option would be the most 'railsy', however using the second option yields a few more options in terms of customization of headers.

Upvotes: 9

Related Questions