我很难通过只知道用户订阅的类别来查找所有文章。每篇文章都可以包含许多类别,我的模型看起来像
文章:
class Article < ActiveRecord::Base
has_many :article_categories
has_many :categories, through: :article_categories
类别:
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表只是文章类别的存储,有两列:article_id&amp;&amp; CATEGORY_ID
那么,如果我有类别id的数组,我如何进行正确的查询,希望能用AR:
@ids = @categories.map { |c| c.id }
答案 0 :(得分:1)
如果我理解你的问题更正,应该这样做:
@articles = Article.joins(:article_categories).where(article_categories: { category_id: @ids })
答案 1 :(得分:0)
您可能有另一个表来跟踪user_categories(用户订阅的类别 - 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