Three Things I Learned This Week - December 02 2016

  • thoughtbot put out a nice form linting tool to help diagnose common form issues. There's a bit of overlap between this and our common ADA toolset, but it's a nice secondary check to make sure forms are implemented well.
  • I've recently had the need to combine url parameters. For example say I have already performed a search - say /search?q=term and the use then chooses to switch locales - /?locale=es. Ideally the search term would be preserved and the final result would be something like /search?q=term&locale=es. This can easily be done with the url_for method and merging the existing params: url_for(request.parameters.merge(locale: "es"))
  • If a user hits a url such as /posts/123, but there is no post with id: 123, Rails will correctly display a 404 response. But why is this? The error raised by Active Record is an ActiveRecord::RecordNotFound, how does that become a 404 response? The answer is in the ActionDispatch::ExceptionWrapper.rescue_responses method. If you run this method in your console, you'll see the mapping:
{ "ActionController::RoutingError" => :not_found,
  "AbstractController::ActionNotFound" => :not_found,
  "ActionController::MethodNotAllowed" => :method_not_allowed,
  "ActionController::UnknownHttpMethod" => :method_not_allowed,
  "ActionController::NotImplemented" => :not_implemented,
  "ActionController::UnknownFormat" => :not_acceptable,
  "ActionController::InvalidAuthenticityToken" => :unprocessable_entity,
  "ActionController::InvalidCrossOriginRequest" => :unprocessable_entity,
  "ActionDispatch::ParamsParser::ParseError" => :bad_request,
  "ActionController::BadRequest" => :bad_request,
  "ActionController::ParameterMissing" => :bad_request,
  "ActiveRecord::RecordNotFound" => :not_found,
  "ActiveRecord::StaleObjectError" => :conflict,
  "ActiveRecord::RecordInvalid" => :unprocessable_entity,
  "ActiveRecord::RecordNotSaved" => :unprocessable_entity }

So an ActiveRecord::RecordNotFound returns a :not_found response, which according to the guides is the 404 status code.

Written by Alex Brinkman who lives and works in Denver, but plays in the mountains.