【问题标题】:Rails optimal query to find all articles with has_many throughRails 最优查询通过 has_many 查找所有文章
【发布时间】:2014-12-07 18:34:21
【问题描述】:

通过只知道用户订阅的类别,我很难找到所有文章。每篇文章可以有很多属于它们的类别,我的模型看起来像

文章:

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

文章类别:

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

article_categories 表只是文章类别的存储,有两列:article_id && category_id

如果我有类别 id 的数组,我该如何进行正确的查询,希望使用 AR:

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

【问题讨论】:

  • Category.find(@categories).map(&amp;:articles) 会为你工作。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

如果我理解您的问题更正,应该这样做:

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

【讨论】:

  • 天哪,这很快而且非常简单。谢谢 :) 我会尽快标记为答案
  • 为什么是-?我没听懂。
  • 无非是错别字。
【解决方案2】:

您可能有另一个表来跟踪 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多