I am trying to build an API using Rails that will inspect the request header for "If-Modified-Since" and render only the objects that were modified past that date. The problem is I am stuck trying to obtain the value from the request header in the controller.
# API
def index
@products = Product.where{updated_at > request.headers["If-Modified-Since"]}
render "v1/products/index"
end
What is the correct way for extracting values from the request header?
First:
If-Modified-Sinceis for HTTP cache validation. Please don’t use it this way. Use a parameter instead.To answer your question:
request.headers[]is the proper way of accessing request headers. For reference,requestis an ActionDispatch::Request object.The problem here is how you’re trying to express the constraint. You’re passing a block into
ActiveRecord‘s#wheremethod, and the block doesn’t make any sense (Symbol#>(String)?). You can express this as a SQL fragment, like:Alternately, you could drop in Squeel, and write: