Query through Active Record Associations.

 

While working on an Ad Server for a current client which I've thoroughly enjoyed writing. I came across some interesting techniques to efficiently query the database using some advanced active record.

These won't be a surprise to the advanced rails developer and I've been using it pretty often in my queries for a while now.

Take the below active record model.

    class Campaign < ActiveRecord::Base

      has_many :advertisements, dependent: :destroy

      has_many :ad_targetings, dependent: :destroy

      has_many :ad_targets, through: :ad_targetings

    end

    class Advertisement < ActiveRecord::Base

      belongs_to :campaign

    end

The ad class has some additionally associations to keep track of ad stats like click counts and impressions counts.

The client and I decided on having the campaigns be the main targeting object where we can target our users with specific criteria and serve them the appropriate ad.

So normally you could pull all advertisements matching the requested targeting params by searching all active campaigns. The system then would subsequently pool all those campaigns' ads into one array. This would cause two queries or one eager loaded query with some additionaly computation to aggregate the ads.

Nah, that's too much work and pretty inelegant, so allow me to present you with a way to query for advertisements with a where clause on it's association.

This technique is essentially querying through an association and it's pretty flexible. It's all active record syntax and one could even go further with SQL strings.

Example query.

    scope :by_target, ->(t) {

      joins(campaign: [:ad_targets])

      .where(ad_targets: {name: t})

    }