首页 > 解决方案 > Rails 从简单模型中提取数据的最有效方法

问题描述

我有两个简单的模型——我必须Campaign从中CampaignCode提取一些已经使用过的模型CampaignCode。因为它是大量数据(仅一个活动的 200k 代码)我想知道哪种方式最有效?

query

CampaignCode.where(state: 'used').count

我认为query这只能用少量数据解决问题,我应该使用include还是一些连接表?

campaign模型

#  created_at         :datetime         not null
#  end_date           :date
#  id                 :bigint(8)        not null, primary key
#  name               :text             not null
#  start_date         :date
#  updated_at         :datetime         not null

class Campaign < ApplicationRecord
  has_many :campaign_codes

  validates :name, presence: true
end

campaign_code模型

#created_at         :datetime         not null
#campaign_id        :bigint(8)
#state              :integer
#uid                :string           not null, primary key
#updated_at         :datetime         not null

class CampaignCode < ApplicationRecord
  self.primary_key = :uid

  belongs_to :campaign

  validates :uid, uniqueness: true
end

标签: ruby-on-railsrubyactiverecord

解决方案


如果您需要速度,您必须使用直接 SQL 并使用数据库的技巧。

我会在您的模型中进行自定义查询(如果是 PostgreSQL):

def self.count_used_codes
  sql = <<-SQL
    SELECT count(*) FROM campaign_codes WHERE state == 'used';
  SQL
  self.find_by_sql(sql)
end

然后使用

CampaignCode.count_used_codes

然后,您还可以根据您的具体使用情况给自己一些优化的灵活性。如果您不担心准确性,您还可以尝试估计的计数,这可能会更快,但这些东西有点超出我的知识范围。

我还看到人们在应用程序中创建一个特定的 sql 文件夹,然后在其中引用复杂的查询以保持它的干净。


推荐阅读