There are a lot of ways to do this, but I searched for the title of this post and got few results.

One solution is to write some custom middleware.

Here’s a great guide: https://lmiller1990.github.io/electic/posts/custom_middleware_in_rails_5.html

You can specify different behavior based on status codes:

  def call(env)
    @status, @headers, @body = @app.call(env)
    if @status == 400
      # do something here
    end
    [@status, @headers, @body]
  end

And you’ll need to add your middleware to the configs:

# config/environments/development.rb
config.middleware.insert_before ActionDispatch::ShowExceptions, MyMiddleware

Suppose you’re building a Rails app for Users who attend many Events, such that a User has_many :events. Now, suppose you want to query for all the Users who have attended an Event that occurred within the last week.

One simple way would be to fetch all the Events and, through those, grab all the Users that attended them, but this wouldn’t work well if we wanted to associate more complex filtering with Users, or use more complex joins.

When you’ve got a problem like that, this article by Richard Jones is phenomenal! I’ve needed to do this at two jobs and have a hard time dredging up this article, so I’m linking it here.

The gist is to use scenic to create and manage database views:

CREATE VIEW newest_events AS
  SELECT DISTINCT ON (user_id) *
  FROM events
  ORDER BY user_id, created_at DESC