Saturday, December 10, 2016

Filtering with ActiveRecord Has Many Through

I wanted to search published episodes that are tagged with a given term. The tag class:

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :episodes, through: :taggings
end

The tagged_with returns all episodes that tagged with the given term including the unpublished ones:

def self.tagged_with(name)
  Tag.find_by!(name: name).episodes
end
The episode model has published class method.

  def self.published
    where('published_at <= ?', Time.now.utc)
  end
We can accomplish this as follows:

tag = Tag.find_by!(name: 'great')
tag.episodes.merge(Episode.published)
Reference

No comments:

Post a Comment