Q:

I have a rails blog where articles can have multiple categories - how do I structure my ArticlesController index action to match on given category id?

So I have a rails blog where articles can have many categories and categories can have many articles, bridging through an ArticleTags join table like so: 
class Article < ApplicationRecord
  ...
  has_many :article_tags,
    primary_key: :id,
    foreign_key: :article_id,
    class_name: 'ArticleTag'

  has_many :categories,
    through: :article_tags,
    source: :category
end

class Category < ApplicationRecord
  ...
  has_many :article_tags,
    primary_key: :id,
    foreign_key: :category_id,
    class_name: 'ArticleTag'

  has_many :articles,
    through: :article_tags,
    source: :article
end

class ArticleTag < ApplicationRecord
  belongs_to :article,
    primary_key: :id,
    foreign_key: :article_id,
    class_name: 'Article'

  belongs_to :category,
    primary_key: :id,
    foreign_key: :category_id,
    class_name: 'Category'
end

If my route is "/categories/:id/articles" I want to return only the articles that match on that category id, but I'm not sure how to structure my controller index action. I got as far as this:
class Api::ArticlesController < ApplicationController
  def index
    if params[:category_id]
#     @articles = Article.where(????)
    else
      @articles = Article.all
    end
    render :index
  end
  ...

Many thanks in advance!

A:

Try this: Category.find(id).articles
c.f: https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

