Rails optimal query to find all articles with has_many via

I am struggling to find all the articles knowing only the user categories I follow. Each article has many categories to which they belong, my models look like

Article:

class Article < ActiveRecord::Base

has_many :article_categories
has_many :categories, through: :article_categories

      

Category:

class Category < ActiveRecord::Base

has_many :article_categories
has_many :articles, through: :article_categories

      

ArticleCategory:

class ArticleCategory < ActiveRecord::Base
  belongs_to :article
  belongs_to :category

      

article_categories table is just a repository for article categories with two columns: article_id && & & category_id

So how do I make the right request, hopefully with AR, if I have an array of category ids:

@ids = @categories.map { |c| c.id }

      

+3


source to share


2 answers


If I understand your correction of the question, this should do:



@articles = Article.joins(:article_categories).where(article_categories: { category_id: @ids })

      

+1


source


You may have another table to track user_categories (categories the user is subscribed to - user_id, category_id)



class User < ActiveRecord::Base

  has_many :category_users
  has_many :categories, :through => :category_users

  def articles
    Article.joins(:article_categories).where( { :category_id => category_users.pluck(:category_id) } ).distinct
  end

end

      

0


source







All Articles