假设您的一个模型中有一个关联,如下所示:
class User
has_many :articles
end现在假设您需要获取3个数组,一个用于昨天写的文章,一个用于过去7天写的文章,另一个用于过去30天写的文章。
当然,您可以这样做:
articles_yesterday = user.articles.where("posted_at >= ?", Date.yesterday)
articles_last7d = user.articles.where("posted_at >= ?", 7.days.ago.to_date)
articles_last30d = user.articles.where("posted_at >= ?", 30.days.ago.to_date)但是,这将运行3个独立的数据库查询。您可以更高效地执行以下操作:
articles_last30d = user.articles.where("posted_at >= ?", 30.days.ago.to_date)
articles_yesterday = articles_last30d.select { |article|
article.posted_at >= Date.yesterday
}
articles_last7d = articles_last30d.select { |article|
article.posted_at >= 7.days.ago.to_date
}当然,这是一个人为的例子,不能保证数组选择确实比数据库查询快,但让我们假设它是快的。
我的问题是:有没有办法(例如一些gem)通过确保你简单地指定关联条件来消除这个问题,并且应用程序本身会决定是否需要执行另一个数据库查询?
ActiveRecord本身似乎没有适当地涵盖这个问题。您必须在每次查询数据库或将关联视为数组之间做出选择。
发布于 2013-04-22 20:40:29
有几种方法可以处理这个问题:
通过在关联定义上指定条件哈希,可以为所需的每个级别创建单独的关联。然后,您可以简单地为您的用户查询快速加载这些关联,并且您将在整个操作中命中数据库3x,而不是每个用户的3x。
class User
has_many articles_yesterday, class_name: Article, conditions: ['posted_at >= ?', Date.yesterday]
# other associations the same way
end
User.where(...).includes(:articles_yesterday, :articles_7days, :articles_30days)你可以做一个group by。
归根结底,你需要分析你的代码,并确定什么对你的应用程序来说是最快的(或者你是否应该为它操心)
发布于 2013-04-23 00:14:54
您可以使用类似以下代码的代码来消除检查查询的必要性。
class User
has_many :articles
def article_30d
@articles_last30d ||= user.articles.where("posted_at >= ?", 30.days.ago.to_date)
end
def articles_last7d
@articles_last7d ||= articles_last30d.select { |article| article.posted_at >= 7.days.ago.to_date }
end
def articles_yesterday
@articles_yesterday ||= articles_last30d.select { |article| article.posted_at >= Date.yesterday }
end
end它的用途:
https://stackoverflow.com/questions/16144284
复制相似问题